简体   繁体   中英

Unable to import CSV file data to mysql table

I am using the code below-

import mysql.connector
import csv

mydb = mysql.connector.connect(host='xxxxx', user='xxxx', passwd='xxxxxx')

cursor = mydb.cursor()
cursor.execute("SHOW DATABASES")
l = cursor.fetchall()

cursor.execute("USE DB ")

with open('details.csv','rt')as f:
    csv_data = csv.reader(f)

   for row in csv_data:
       cursor.execute ('INSERT INTO student (id,name,age,course) VALUES (%s,%s,%s,%s)',row)
cursor.close()
mydb.commit()
mydb.close()

I am getting the following error- "ProgrammingError: Not all parameters were used in the SQL statement" python 3.x,windows7,Mysql 2012 version.

In this case, the main problem is the string format. I did't know what object is row , in your error it is a list, so using each element will solve the issue.

for row in csv_data:
       cursor.execute ('INSERT INTO student (id,name,age,course) VALUES (%s,%s,%s,%s)',
row[0], row[1], row[2], row[3])
for row in csv_data:
    listval = []
    for col in row:
        listval.append(col)

    cursor.execute ('INSERT INTO student (id,name,age,course) VALUES (%s,%s,%s,%s) ', listval)

This will work :))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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