Python写入MySQL数据库to_sql()一文详解+代码展示

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: Python写入MySQL数据库to_sql()一文详解+代码展示

前言


用Python写数据库操作的脚本时,少不了的是写入和读取操作。但这类方法参数说明大多都差不多,例如前段时间写的关于处理JSON文件的两类函数read_json,to_json。读取和写入这两种方法往往都是相对的,而当掌握了Pandas的dataframe数据结构的各种操作时,那么我们的插入方式将可以多种多样,对数据处理的方式也可以相对更加灵活。此篇文章将根据解读官方文档的方式具体使用每个参数的不同赋值,来展示结果。


一、函数基本语法

DataFrame.to_sql(name, con, schema=None, if_exists='fail', 
index=True, index_label=None, chunksize=None, dtype=None)

该函数的具体功能为实现将pandas的数据结构存储对象Dataframe写入到SQL数据库中。其中我们要写入的SQL数据库中是应该存在数据库和表格的,不然会保存。而且该表是有权限能够写入的,这些是前提条件。


二、参数说明


name : string
Name of SQL table.
con : sqlalchemy.engine.Engine or sqlite3.Connection
Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects.
schema : string, optional
Specify the schema (if database flavor supports this). If None, use default schema.
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’
How to behave if the table already exists.
fail: Raise a ValueError.
replace: Drop the table before inserting new values.
append: Insert new values to the existing table.
index : boolean, default True
Write DataFrame index as a column. Uses index_label as the column name in the table.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and index is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, optional
Rows will be written in batches of this size at a time. By default, all rows will be written at once.
dtype : dict, optional
Specifying the datatype for columns. The keys should be the column names and the values should be the SQLAlchemy types or strings for the sqlite3 legacy mode.
Raises: 
ValueError
When the table already exists and if_exists is ‘fail’ (the default).

1.name


该name为SQL表的名字,这是必须输入的参数,指定写入的表。


2.con


con为python连接sql的sqlalchemy.engine,该参数也为必须输入的参数,可以使用SQLAlchemy数据库支持的连接引擎。该引擎可以引入:


from sqlalchemy import create_engine
import pymysql

从而创建连接引擎:

#创建引擎
engine=create_engine('mysql+pymysql://用户名:密码@主机名/数据库?charset=utf8')

3.schema


指定架构(如果database flavor支持此功能)。如果没有,则使用默认架构。pandas中get_schema()方法是可以编写sql的写入框架的,没用传入的话就是普通的Dataframe读入形式。


4.if_exists


该参数为当存在表格时我们应该选择数据以怎样的方式写入到这张表格之中,共有三种方式选择:

  • fail:当存在表格时候自动弹出错误ValueError
  • replace:将原表里面的数据给替换掉
  • append:将数据插入到原表的后面


我们首先引入库来实践操作一下:


c76d713f5efa45ff9ecbd97fcdb51b7c.png

这是表格,里面已经有了数据,下面我们进行插入实验


from sqlalchemy import create_engine
import pymysql
import pandas as pd
import datetime
# 打开数据库连接
conn = pymysql.connect(host='localhost',
                       port=3306,
                       user='root',
                       passwd='xxxx',
                       charset = 'utf8'
                       )
# 使用 cursor() 方法创建一个游标对象 cursor                      
cursor = conn.cursor()
#创建引擎
engine=create_engine('mysql+pymysql://root:xxxx@localhost/mysql?charset=utf8')
date_now=datetime.datetime.now()
data={'id':[888,889],
                       'code':[1003,1004],
                        'value':[2000,2001],
                        'time':[20220609,20220610],
                        'create_time':[date_now,date_now],
                        'update_time':[date_now,date_now]}
insert_df=pd.DataFrame(data)
insert_df.to_sql('metric_valuetest',engine,if_exists='fail')

if_exists默认为fail则当存在表时,升起错误


4a089f4499d94febb1d0b35b85865c1a.png

若表格为没有命名的表格,则会自动创建表格:

from sqlalchemy import create_engine
import pymysql
import pandas as pd
import datetime
# 打开数据库连接
conn = pymysql.connect(host='localhost',
                       port=3306,
                       user='root',
                       passwd='xxxx',
                       charset = 'utf8'
                       )
# 使用 cursor() 方法创建一个游标对象 cursor                      
cursor = conn.cursor()
#创建引擎
engine=create_engine('mysql+pymysql://root:xxxx@localhost/mysql?charset=utf8')
date_now=datetime.datetime.now()
data={'id':[888,889],
                       'code':[1003,1004],
                        'value':[2000,2001],
                        'time':[20220609,20220610],
                        'create_time':[date_now,date_now],
                        'update_time':[date_now,date_now]}
insert_df=pd.DataFrame(data)
insert_df.to_sql('create_one',engine,if_exists='fail')

f13b9d2a8fdf4e35919299e3768141ef.png

但是不推荐这样做,这样做将并不会指定创建表每个字段的详细信息和类型,看DDL就可以看出:


fcc88892427b4ab2aea16b1b498ea060.png

很容易出现问题,我们应该先创建个符合每个字段含义和类型的表格再写入其中。

append直接添加在原来数据后面:

date_now=datetime.datetime.now()
data={'id':[888,889],
                       'code':[1003,1004],
                        'value':[2000,2001],
                        'time':[20220609,20220610],
                        'create_time':[date_now,date_now],
                        'update_time':[date_now,date_now],
                         'source':['python','python']}
insert_df=pd.DataFrame(data)
'''schema_sql={ 'id': sqlalchemy.types.BigInteger(length=20),
             'code': sqlalchemy.types.BigInteger(length=20),
             'value': sqlalchemy.types.BigInteger(length=20),
             'time':  sqlalchemy.types.String(length=50),
             'create_time':  sqlalchemy.types.Datetime(length=50),
             'update_time':  sqlalchemy.types.Datetime(length=50),
                 }'''
insert_df.to_sql('metric_valuetest',engine,if_exists='append',index=False)

24b347ae3c8b481ca36080abb31564e4.png

这里我们首先要吧index索引给关闭,不然会出现:

b49f6bc1fdec427993db60987b51de37.png

index也算进写入mysql数据库中,导致原表中不存在index字段不能插入的问题。


insert_df.to_sql('metric_valuetest',engine,if_exists='replace',index=False)


replace将直接把原表数据给直接替换掉,要小心使用 。


d245e7a143554199b414c565cf721451.png

5.index


默认为True等于存在第一行,列名为index的列,也可以先设定好行索引为哪一列防止插入的时报错


ececd70b59b74572b686a24e822b3499.png

6.index_label


索引列的列标签。如果未给定任何值(默认值)且index为True,则使用索引名称。如果数据帧使用多索引,则应给出序列。也就是如果设定的index为True,可以给index设定列名。

insert_df.to_sql('reate_one',engine,if_exists='replace',index=True,index_label='god')

6a526fdb145c4fdb9b57b5c5e346fd99.png


7.chunksize


一次将按此大小成批写入行。默认情况下,将一次写入所有行。可以设定一次写入的数量,避免一次写入数据量过大导致数据库崩溃。


8.dtype


指定列的数据类型。键是列名,值是sqlite3模式的SQLAlchemy类型或字符串。可以去 sqlalchemy 的官方文档查看所有的sql数据类型:


‘TypeEngine’, ‘TypeDecorator’, ‘UserDefinedType’, ‘INT’, ‘CHAR’, ‘VARCHAR’, ‘NCHAR’, ‘NVARCHAR’, ‘TEXT’, ‘Text’, ‘FLOAT’, ‘NUMERIC’, ‘REAL’, ‘DECIMAL’, ‘TIMESTAMP’, ‘DATETIME’, ‘CLOB’, ‘BLOB’, ‘BINARY’, ‘VARBINARY’, ‘BOOLEAN’, ‘BIGINT’, ‘SMALLINT’, ‘INTEGER’, ‘DATE’, ‘TIME’, ‘String’, ‘Integer’, ‘SmallInteger’, ‘BigInteger’, ‘Numeric’, ‘Float’, ‘DateTime’, ‘Date’, ‘Time’, ‘LargeBinary’, ‘Binary’, ‘Boolean’, ‘Unicode’, ‘Concatenable’, ‘UnicodeText’, ‘PickleType’, ‘Interval’, ‘Enum’, ‘Indexable’, ‘ARRAY’, ‘JSON’]  

from sqlalchemy import create_engine
import sqlalchemy
import pymysql
import pandas as pd
import datetime
from sqlalchemy.types import INT,FLOAT,DATETIME,BIGINT
date_now=datetime.datetime.now()
data={'id':[888,889],
                       'code':[1003,1004],
                        'value':[2000,2001],
                        'time':[20220609,20220610],
                        'create_time':[date_now,date_now],
                        'update_time':[date_now,date_now],
                         'source':['python','python']}
insert_df=pd.DataFrame(data)
schema_sql={ 'id':INT,
             'code': INT,
             'value': FLOAT(20),
             'time': BIGINT,
             'create_time':  DATETIME(50),
             'update_time':  DATETIME(50)
                 }
insert_df.to_sql('create_two',engine,if_exists='replace',index=False,dtype=schema_sql)

cb797fb8f2644decbfa2308a85667acc.png8c3c88f9561642eaad3a8285cef574f5.png

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
17小时前
|
Python
Python中的装饰器:提升代码可读性与复用性
Python中的装饰器是一种强大的工具,能够提升代码的可读性和复用性。本文将深入探讨装饰器的原理、用法以及在实际项目中的应用,帮助读者更好地理解和利用这一特性,提升代码质量和开发效率。
|
1天前
|
监控 Python
Python中的装饰器:提升代码可读性与可维护性
Python中的装饰器是一种强大的工具,可以在不修改函数源代码的情况下,增加新的功能。本文将介绍装饰器的基本概念,以及如何使用装饰器来提升代码的可读性和可维护性。通过实例演示,读者将了解装饰器在各种场景下的灵活运用,从而更好地理解并应用于实际开发中。
|
1天前
|
缓存 Python
Python中的装饰器:提升代码可读性与灵活性
在Python编程中,装饰器是一种强大的工具,可以通过在函数或方法周围包装额外的功能来提升代码的可读性和灵活性。本文将深入探讨装饰器的概念、用法和实际应用,帮助读者更好地理解并运用这一Python编程的利器。
|
2天前
|
缓存 并行计算 Serverless
优化Python代码性能的5个技巧
在日常Python编程中,代码性能的优化是一个重要的议题。本文介绍了5个实用的技巧,帮助你提高Python代码的执行效率,包括使用适当的数据结构、优化循环结构、利用内置函数、使用生成器表达式以及并行化处理。通过这些技巧,你可以更高效地编写Python代码,提升程序的性能和响应速度。
|
3天前
|
Python
探索Python中的装饰器:提升代码灵活性与可维护性
Python中的装饰器是一种强大的工具,可以在不改变原有代码结构的情况下,动态地添加功能或修改函数的行为。本文将深入探讨装饰器的原理、常见用法以及如何利用装饰器提升代码的灵活性和可维护性。
|
4天前
|
机器学习/深度学习 自然语言处理 算法
Python遗传算法GA对长短期记忆LSTM深度学习模型超参数调优分析司机数据|附数据代码
Python遗传算法GA对长短期记忆LSTM深度学习模型超参数调优分析司机数据|附数据代码
|
4天前
|
数据可视化 Python
python中Copula在多元联合分布建模可视化2实例合集|附数据代码
python中Copula在多元联合分布建模可视化2实例合集|附数据代码
|
2月前
|
SQL 关系型数据库 MySQL
用 Python 连接数据库并进行查询。
【2月更文挑战第12天】【2月更文挑战第32篇】用 Python 连接数据库并进行查询。
|
4月前
|
SQL 关系型数据库 MySQL
python连接数据库
python连接数据库
29 0
|
4月前
|
SQL 关系型数据库 数据库连接
Python 连接 SQL 数据库 -pyodbc
以下是如何在 Python 中使用 pyodbc 连接到 SQL 数据库的基本步骤和详解
57 0