Not enough parameters for the SQL statement error

Question:

i’m trying to import csv file into SQL table but i received this error "Not enough parameters for the SQL statement" i think that it’s something in the SQL query …

import mysql.connector as msql
import csv

conn = msql.connect(host='localhost', user='root', password='', database='test_database')
my_cursor = conn.cursor()

csv_data = csv.reader(open('lycee.csv'))
header = next(csv_data)

print('Importing the CSV Files')
 for row in csv_data:
    print(row)
    my_cursor.execute("INSERT INTO lycee(date,etudiant,universite,age) 
      VALUES(%d,%s,%s,%d)", row)
conn.commit()
Asked By: Atef Hmaied

||

Answers:

my_cursor.execute("INSERT INTO lycee(date,etudiant,universite,age) 
  VALUES(%d,%s,%s,%d)", row)

Row is an list or dictionary here. You’re asking for 4 parameters to be provided but only provide 1 to place them on there.

Row would be something like this:

[2020-01-01,me,universityname,32]

So something like:

row[0]

could provide the date, assuming the output of the csv.reader is a list of lists. Do the same for the other values as well.

Answered By: JustLudo

Asssuming lycee.csv has 4 columns

When you do

my_cursor.execute("INSERT INTO lycee(date,etudiant,universite,age) 
    VALUES(%d,%s,%s,%d)", row)

you actually pass 1 array argument, but 4 expected. All you need to do is to unwrap your array

my_cursor.execute("INSERT INTO lycee(date,etudiant,universite,age) 
  VALUES(%d,%s,%s,%d)", *row)
Answered By: sudden_appearance