我无法执行 Python 文件将 CSV 文件导入 MySQL 表。
import csv
import mysql.connector
mydb = mysql.connector.connect(
host='localhost',
user='root',
passwd='',
database='ricoh_oms'
)
cursor = mydb.cursor()
csv_data = csv.reader(open("slv_internal.csv"))
for row in csv_data:
cursor.execute("INSERT INTO slv_internal (GID, FullName, CostCenter) VALUES (%s, %s, %s)")
mydb.commit()
cursor.close()
print("Done")
我是新手,不明白错误中标记 %s 的含义。感谢您的帮助。错误是:
错误:
"mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s, %s)' at line 1"
最佳答案
您正在尝试执行参数化查询
示例:
insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
在代码中您缺少参数:
cursor.execute("INSERT INTO slv_internal (GID, FullName, CostCenter) VALUES (%s, %s, %s)", ("value1","value2","value3"))
一些文档:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
关于python - 使用Python将CSV导入MySQL表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056523/