尝试使用 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)
读取工作正常,但 to_sql
有错误:
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Wrong number of arguments during string formatting
为什么它看起来像是在尝试使用 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'
最佳答案
使用引擎代替 raw_connection()
工作:
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)
data.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)
不清楚为什么当我昨天尝试这个时它给了我之前的错误。
关于python - 使用 SQLAlchemy、to_sql 使用 pandas 写入 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30631325/