簡體   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