这只是一个笔记
只为记录自己在用pandas的时候遇到的一些坑
pandas.to_sql()
pandas的to_sql()方法可以向数据库中插入数据,可以用非常少量的代码代码来实现。
def to_sql(
self,
name,
con,
schema=None,
if_exists="fail",
index=True,
index_label=None,
chunksize=None,
dtype=None,
method=None,
):
第一个坑:con 这里的con并不是pymysql的con,这里的con需要用到sqlalchemy模块,用这个模块来创建一个连接数据库的引擎。con需要用到这个引擎来链接数据库
engine = create_engine("mysql+pymysql://用户名:密码@地址:端号/数据库名?charset=utf8")
第二个坑:if_exists,这个并不是判断数据是否存在,页是判断数据库是否存在。这是说明文档,可以看到如果选择了’replace’,在插入数据之前会先把存在的数据库删除掉(很严重的问题,非常值得注意)。
"""
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
"""
index : bool, 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.
"""
需要把这两个参数结合起来看,如果数据库里面有自增id或者并不需要把df的index作为一个列写入mysql, index设置成False就可以了。如果需要把df的index作为一个列写入mysql,把index设置成True,并且设置一下index_lable的值作为字段
所以要这样写:
# 创建连接引擎
engine = create_engine("mysql+pymysql://用户名:密码@地址:端号/数据库名?charset=utf8")
# 把df存储mysql数据库
df.to_sql(
name='表名',
con=engine,
if_exists='append',
index=False,
)