[运行我想将csv文件中的数据插入mysql的python代码时出现此错误...
Traceback (most recent call last):
File "./mongo2sql.py", line 16, in <module>
mycursor.execute(drop, ctbl)
File "/usr/local/lib64/python3.6/site-packages/mysql/connector/cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/usr/local/lib64/python3.6/site-packages/mysql/connector/connection_cext.py", line 632, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
这是我的py代码:
#!/usr/bin/python3
import mysql.connector
mydb = mysql.connector.connect(
host="host",
user="user",
passwd="user",
database="db"
)
mycursor = mydb.cursor()
drop = "Drop Table User;"
ctbl = "Create Table db.User (`_id` VARCHAR(255) not null primary key,`accountStatus` VARCHAR(255) null,`active` BOOL null,`allowedPartners` VARCHAR(255) null,`allowedProviders` VARCHAR(255) null,`capabilities` VARCHAR(255) null,`createdDateTime` DATETIME null,`firstName` VARCHAR(255) null,`lastName` VARCHAR(255) null,`mail` VARCHAR(255) null,`role` VARCHAR(255) null,`sourcePartnerId` VARCHAR(255) null)"
mycursor.execute(drop, ctbl)
mydb.commit()
print("Table Dropped & New created \n Working on inserting data...")
sql = "INSERT INTO vdmUser (_id,accountStatus,active,allowedPartners,allowedProviders,capabilities,createdDateTime,firstName,lastName,mail,role,sourcePartnerId) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,)"
with open("userlist.csv", "r") as a_file:
for line in a_file:
stripped_line = line.strip()
print(stripped_line)
mycursor.execute(sql,stripped_line)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
我是python的新手,因此可以接受任何指导。
您必须将csv解析为单独的组件,并将结果迭代器传递给.execute()
。
import csv
with open("userlist.csv", newline='') as a_file:
reader = csv.reader(a_file)
for row in reader:
print(row)
# you may want to validate your csv content's before,
# but anyway...
mycursor.execute(sql, row)
# better to commit only once at the end of the import
# 1/ it's much faster and 2/ it's atomic, so if anything
# goes wrong you can just fix the csv and relaunch the
# whole import (else you'd get a partial import)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
据说,mysql / mariadb already provides support代表tabular data import