Shu*_*m R 3 python python-2.7 python-3.x pandas
我在pandas dataframe df中有一个表.
product_id_x product_id_y count date
0 288472 288473 1 2016-11-08 04:02:07
1 288473 2933696 1 2016-11-08 04:02:07
2 288473 85694162 1 2016-11-08 04:02:07
Run Code Online (Sandbox Code Playgroud)
我想将此表保存在mysql数据库中.
我正在使用MySQLdb包.
import MySQLdb
conn = MySQLdb.connect(host="xxx.xxx.xx.xx", user="name", passwd="pwd", db="dbname")
df.to_sql(con = conn, name = 'sample_insert', if_exists = 'append', flavor = 'mysql', index = False)
Run Code Online (Sandbox Code Playgroud)
我用这个查询把它放在我的数据库中.
但我得到错误.
ValueError: database flavor mysql is not supported
Run Code Online (Sandbox Code Playgroud)
我的数据类型是所有列的str.
type(df['product_id_x'][0]) = str
type(df['product_id_y'][0]) = str
type(df['count'][0]) = str
type(df['date'][0]) = str
Run Code Online (Sandbox Code Playgroud)
我不想使用sqlalchemy或其他软件包,任何人都可以告诉我这里的错误是什么.提前致谢
pandas版本0.19中不推荐使用'mysql'.您必须使用sqlalchemy中的引擎来创建与数据库的连接.
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://USER:"+'PASSWORD'+"@localhost/DATABASE")
df.to_sql(con=engine, if_exists='append', index=False)
Run Code Online (Sandbox Code Playgroud)
定义引擎时,需要指定用户,密码,主机和数据库.在您的具体情况下,这应该是这样的:
engine = create_engine("mysql+mysqldb://name:pwd@xxx.xxx.xx.xx/dbname")
Run Code Online (Sandbox Code Playgroud)