我正在try 解决我认为很简单的问题:将Pandas中的数据框导出到MySQL数据库中.

有一个用于在PANAS中整理数据以保存CSV格式的刮取器

**title, summary, url** #header
  abc,   summary, some_url

但我想将数据帧直接发送到具有相同三列格式的MySQL数据库.

到目前为止我的代码是:

import mysql.connector

# Connect to the database
conn = mysql.connector.connect(user='root', password='somepassword', host='localhost', port='3306', database='db')

# Write the DataFrame to the database
df.to_sql(name='table_name', con=conn, if_exists='replace', index=False)

# Close the connection
conn.close()

但这将返回一条错误消息:

pandas.errors.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Not all parameters were used in the SQL statement

我该怎么解决这个问题?

最新情况:

我读到我可能不得不使用SqlalChemy,但如果可能的话,我真的想坚持使用Pandas 的解决方案.

推荐答案

您仍然可以使用PANDA解决方案,但是您必须使用sqlalchemy.create_engine而不是mysql.connector.connect,因为to_sql需要"sqlalchemy.engine.(Engine or Connection)sqlite3.Connection"作为con参数.请参见那里的reference和示例.这应该可以很好地工作:

import sqlalchemy

# Connect to the database
conn = sqlalchemy.create_engine(
'mysql+mysqlconnector://root:somepassword@localhost:3306/db')

# Write the DataFrame to the database
df.to_sql(name='table_name', con=conn, if_exists='replace', index=False)

# Close the connection
conn.close()

Mysql相关问答推荐

如何在循环查询中删除默认架构?

根据上一行S列结果计算列的查询

如何防止程序中计数器出错

没有 ORDER BY 的查询性能很高,有 ORDER BY 的查询速度慢得像爬行一样

按唯一列排序,但保持匹配的列在一起

获取每个参数的记录,不重复

使用mysql查询获取不关注user1的user3

如何更新一个巨大的表的 50k 行?

如何在 Shopware 6 DAL 中实施 Haversine 公式?

SQL:如何为给定组中的所有记录 Select 一列与另一列不匹配的位置

MySQL DISTINCT 日期仅返回特定表的 1 个值.相同的查询适用于其他表

MySQL表中给定字段的每个不同值的连续记录形成对

限制正则​​表达式中多字符通配符的范围

在 MySQL 中转换 JSON 数组值

Mysql insert with loop out of select 语句

mysql从另一个表中 Select 不相等的值

MAMP mysql 服务器无法启动.没有mysql进程正在运行

问号在 MySQL 中WHERE column = ?的意义是什么?

判断多个列的一个值

如何将数组存储到mysql中?