如何通过mysqldb将pandas数据框插入数据库? [英] How to insert pandas dataframe via mysqldb into database?

查看:102
本文介绍了如何通过mysqldb将pandas数据框插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从python连接到本地mysql数据库,并且可以创建,选择并插入单个行.

I can connect to my local mysql database from python, and I can create, select from, and insert individual rows.

我的问题是:我可以直接指示mysqldb获取整个数据帧并将其插入到现有表中,还是需要遍历行?

My question is: can I directly instruct mysqldb to take an entire dataframe and insert it into an existing table, or do I need to iterate over the rows?

在任何一种情况下,对于一个具有ID和两个数据列以及一个匹配数据框的非常简单的表,python脚本的外观如何?

In either case, what would the python script look like for a very simple table with ID and two data columns, and a matching dataframe?

推荐答案

更新:

现在有一个 to_sql 方法,这是首选的方法,而不是write_frame:

df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')

也请注意:语法可能会在熊猫0.14 ...

您可以使用 MySQLdb 建立连接:

from pandas.io import sql
import MySQLdb

con = MySQLdb.connect()  # may need to add some other options to connect

write_frameflavor设置为'mysql'意味着您可以写入mysql:

Setting the flavor of write_frame to 'mysql' means you can write to mysql:

sql.write_frame(df, con=con, name='table_name_for_df', 
                if_exists='replace', flavor='mysql')

参数if_exists告诉熊猫表是否已存在该如何处理:

The argument if_exists tells pandas how to deal if the table already exists:

if_exists: {'fail', 'replace', 'append'},默认为'fail'
    fail:如果存在表,则什么也不做.
    replace:如果存在表,则将其删除,重新创建并插入数据.
    append:如果存在表,则插入数据.如果不存在则创建.

if_exists: {'fail', 'replace', 'append'}, default 'fail'
     fail: If table exists, do nothing.
     replace: If table exists, drop it, recreate it, and insert data.
     append: If table exists, insert data. Create if does not exist.

尽管 write_frame文档当前建议它仅在sqlite上起作用,mysql似乎受支持,并且实际上有很多 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆