繁体   English   中英

Python 中的这条 SQL 语句有什么问题?

[英]What is wrong with this SQL statement in Python?

我正在使用 Python 和 MySQL 数据库,并试图遍历 CSV 文件中的行并将它们插入我的数据库中。 我有以下几点:

import mysql.connector
import pandas as pd

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="root",
    database="mydb")

cursor = mydb.cursor()
cursor.execute("SET FOREIGN_KEY_CHECKS=0")
csv_data = pd.read_csv("file path")
sql = "INSERT INTO table (ID, SecondID, StartDate, EndDate) VALUES (%s, %s, %s, %s)"
for index, row in csv_data.iterrows():
    cursor.execute(sql, row)
cursor.execute("SET FOREIGN_KEY_CHECKS=1")
mydb.commit()
cursor.close()
mydb.close()

我看不出 SQL 有什么问题。 得到以下错误:

您的 SQL 语法有错误; 检查与您的 MySQL 服务器版本相对应的手册,了解在 '%s, %s, %s, %s)' 附近使用的正确语法

注意- 其余代码似乎工作正常,如果我插入特定值,SQL 工作正常,但是当我尝试使用 %s 构造时,它会失败,但我看到的其他响应似乎建议将此作为正确的语法。

请帮助-我做错了什么?

我认为你最好使用 pandas to_sql 函数。
我不确定mysql.connector是否有效,所以我将使用sqlalchemy
它看起来像这样:

ENGINE = sqlalchemy.create_engine('mysql+pymysql://root:root@localhost:3306/mydb')
with ENGINE.connect() as connection:
    ENGINE.execute("SET FOREIGN_KEY_CHECKS=0")
    csv_data.to_sql('table_name', connection, if_exists='append', index=False)
    ENGINE.execute("SET FOREIGN_KEY_CHECKS=1")

看起来问题在于您正在调用查询而没有对值进行转义。

execute函数获取一个类而不是一个数组

for index, row in csv_data.iterrows():
    cursor.execute(sql, row)

您应该生成一个包含所有值的数组,然后调用查询。

就像是:

for index, row in csv_data.iterrows():
    params = map(lambda x : x.value, row)
    cursor.execute(sql,params)

请注意,数组的大小必须与值参数的大小相同。 在这种情况下 4

谢谢你,这非常有帮助,我做了一个小改动,现在效果很好。 这是我使用的最终解决方案:

import pandas as pd
import sqlalchemy

engine = sqlalchemy.create_engine('mysql+pymysql://root:root@localhost:3306/mydb')

csv_data = pd.read_csv("file path")
engine.execute("SET FOREIGN_KEY_CHECKS=0")

with engine.connect() as connection:
    csv_data.to_sql('table', connection, if_exists='append', index=False)

engine.execute("SET FOREIGN_KEY_CHECKS=1")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM