python - 使用Python将CSV导入MySQL表

标签 python mysql

我无法执行 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/

相关文章:

mysql - sql - 查找两个图点之间的成本

python - n个集合的python "set.intersection"的时间复杂度

python - 使用 dtype float64 创建 pandas dataframe 更改其条目的最后一位数字(相当大的数字)

python - python图像库(PIL)中的getbbox方法不起作用

mysql - 更新一张表中一列的两行

根据最高击杀次数对 PHP 表用户进行排名

php - Codeigniter/PHP,2 个 Mysql 表,多个查询

python - 关于我制作的小型转换器的IF语句问题

python - 无论级别设置如何,如何始终将日志消息写入文件

mysql - 如何获取可由给定字母组成的所有单词?