python - 使用 SQLAlchemy、to_sql 使用 pandas 写入 MySQL 数据库

标签 python mysql pandas sqlalchemy mysql-connector

尝试使用 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/

相关文章:

python - 如何将 PySpark 函数的返回类型指定为数据框?

python - python如何知道在字符串文字和变量之间添加一个空格?

python - 抓取时无法获取头条内容

mysql - 如何提高记录集处理的性能

mysql - 选择数组内爆中映射 id 的位置

mysql - Spring Boot 和 MySql - 无法使用新的服务数据库用户名/密码

python - 使用 pandas 跨多个列进行选择

python-3.x - 新数据帧是旧数据帧中多列上 value_counts 的结果

python - 使用 kubernetes 客户端 corev1api 运行 `connect_get_namespaced_pod_exec` 给出错误请求

python - pandas nlargest 返回超过 n 行