繁体   English   中英

使用Python将CSV导入MySQL表

[英]Using Python to Import CSV to a MySQL table

我无法执行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):您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取正确的语法以在'%s,%s,%s附近使用” '在第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/zh-CN/connector-python-api-mysqlcursor-execute.html

暂无
暂无

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

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