简体   繁体   English

使用sqlalchemy将pandas dataframe插入mysql

[英]Insert pandas dataframe to mysql using sqlalchemy

I simply try to write a pandas dataframe to local mysql database on ubuntu. 我只是尝试将pandas数据帧写入ubuntu上的本地mysql数据库。

from sqlalchemy import create_engine
import tushare as ts

df = ts.get_tick_data('600848', date='2014-12-22')
engine = create_engine('mysql://user:passwd@127.0.0.1/db_name?charset=utf8')
df.to_sql('tick_data',engine, flavor = 'mysql', if_exists= 'append')

and it pop the error 它会弹出错误

biggreyhairboy@ubuntu:~/git/python/fjb$ python tushareDB.py 
Error on sql SHOW TABLES LIKE 'tick_data'
Traceback (most recent call last):
 File "tushareDB.py", line 13, in <module>
   df.to_sql('tick_data', con = engine,flavor ='mysql', if_exists= 'append')
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1261, in to_sql
    self, name, con, flavor=flavor, if_exists=if_exists, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pandas/io/sql.py", line 207, in write_frame
    exists = table_exists(name, con, flavor)
  File "/usr/lib/python2.7/dist-packages/pandas/io/sql.py", line 275, in table_exists
    return len(tquery(query, con)) > 0
  File "/usr/lib/python2.7/dist-packages/pandas/io/sql.py", line 90, in tquery
    cur = execute(sql, con, cur=cur)
  File "/usr/lib/python2.7/dist-packages/pandas/io/sql.py", line 53, in execute
    con.rollback()
AttributeError: 'Engine' object has no attribute 'rollback'

the dataframe is not empty, database is ready without tables, i have tried other method to create table in python with mysqldb and it works fine. 数据帧不是空的,数据库已经准备好没有表,我已经尝试了使用mysqldb在python中创建表的其他方法,并且它工作正常。

a related question: Writing to MySQL database with pandas using SQLAlchemy, to_sql but no actual reason was explained 一个相关的问题: 使用SQLAlchemy,to_sql用pandas写入MySQL数据库,但没有解释实际原因

You appear to be using an older version of pandas. 您似乎使用的是旧版本的pandas。 I did a quick git bisect to find the version of pandas where line 53 contains con.rollback() , and found pandas at v0.12, which is before SQLAlchemy support was added to the execute function. 我做了一个快速的git bisect来找到pandas的版本,其中第53行包含con.rollback() ,并在v0.12找到pandas,这是在SQLAlchemy支持被添加到execute函数之前。

If you're stuck on this version of pandas, you'll need to use a raw DBAPI connection: 如果您坚持使用此版本的pandas,则需要使用原始DBAPI连接:

df.to_sql('tick_data', engine.raw_connection(), flavor='mysql', if_exists='append')

Otherwise, update pandas and use the engine as you intend to. 否则,请更新pandas并按预期使用引擎。 Note that you don't need to use the flavor parameter when using SQLAlchemy: 请注意,使用SQLAlchemy时不需要使用flavor参数:

df.to_sql('tick_data', engine, if_exists='append')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM