pandas Python 熊猫 to_sql '追加'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26765863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pandas to_sql 'append'
提问by j riot
I am trying to send monthly data to a MySQL database using Python's pandas to_sql command. My program runs one month of data at a time and I want to append the new data onto the existing database. However, Python gives me an error:
我正在尝试使用 Python 的 pandas to_sql 命令将每月数据发送到 MySQL 数据库。我的程序一次运行一个月的数据,我想将新数据附加到现有数据库中。但是,Python 给了我一个错误:
_mysql_exceptions.OperationalError: (1050, "Table 'cps_basic_tabulation' already exists")
Here is my code for connecting and exporting:
这是我的连接和导出代码:
conn = MySQLdb.connect(host = config.get('db', 'host'),
user = config.get('db', 'user'),
passwd = config.get('db', 'password'),
db = 'cps_raw')
combined.to_sql(name = "cps_raw.cps_basic_tabulation",
con = conn,
flavor = 'mysql',
if_exists = 'append')
I have also tried using:
我也试过使用:
from sqlalchemy import create_engine
Replacing conn = MySQLdb.connect... with:
将 conn = MySQLdb.connect... 替换为:
engine = mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
conn = engine.connect().connection
Any ideas on why I cannot append to a database?
关于为什么我不能附加到数据库的任何想法?
Thanks!
谢谢!
回答by joris
Starting from pandas 0.14, you have to provide directly the sqlalchemy engine, and not the connection object:
从 pandas 0.14 开始,您必须直接提供 sqlalchemy engine,而不是连接对象:
engine = create_engine("mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>")
combined.to_sql("cps_raw.cps_basic_tabulation", engine, if_exists='append')

