尝试使用to_sql将pandas数据帧写入MySQL表.以前一直在使用flavor ='mysql',但是它将来会被折旧并且想要开始转换到使用SQLAlchemy引擎.
示例代码:
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)
cnx = engine.raw_connection()
data = pd.read_sql('SELECT * FROM sample_table', cnx)
data.to_sql(name='sample_table2', con=cnx, if_exists = 'append', index=False)
Run Code Online (Sandbox Code Playgroud)
读取工作正常,但to_sql有错误:
DatabaseError:sql上的执行失败'SELECT name FROM sqlite_master WHERE type ='table'AND name =?;':字符串格式化过程中参数数量错误
为什么看起来它试图使用sqlite?sqlalchemy与mysql,特别是mysql.connector的正确使用是什么?
我也尝试将引擎作为连接传递,这给了我一个引用没有游标对象的错误.
data.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)
>>AttributeError: 'Engine' object has no attribute 'cursor'
Run Code Online (Sandbox Code Playgroud)