Home > Mobile >  Error importing CSV With Python to MYSQL - TypeError: not enough arguments for format string
Error importing CSV With Python to MYSQL - TypeError: not enough arguments for format string

Time:12-15

I'm facing a problem trying to insert a CSV file with 800 records in the database. This gives me the following error: MySQLdb.ProgrammingError: not enough arguments for format string. I already checked and the exchanges and variables are correct, could you help me what would this problem be? Here is the code:

import MySQLdb
import csv
conn = MySQLdb.connect(host="127.0.0.1", user="root", password="", database="csm")

cursor = conn.cursor()
csv_data = csv.reader(open('teste2.csv'))
header = next(csv_data)

for row in csv_data:
    print(row)
    cursor.execute(
        "INSERT INTO estoque1 (release, official, order, date, product, client, sales, sales, quant) VALUES (%s, %s, %s, %s, %s ,%s ,%s ,%s ,%s)", row)

conn.commit()
cursor.close()

I'm facing this error but idk how to solve this. Anyone have some tips about this how can i solve?

Follow the image:enter image description here

CodePudding user response:

Because you're passing the array as an argument while the execute() function expects all the elements of the array as a single argument.

You should be able to pass the array like this:

cursor.execute(
    "INSERT INTO estoque1 (release, official, order, date, product, client, sales, sales, quant) VALUES (%s, %s, %s, %s, %s ,%s ,%s ,%s ,%s)",
    *row
)

Note the asterisk.

CodePudding user response:

The Problem is that you only pass one parameter (the row list) to the 9 placeholders in your string. To fix that you need either convert the list to a tuple, use the "*" operator to unpack the list or pass all the values of the list individually.

Use the * operator to unpack:

row = [1, 2, 3, 4]
"%s %s %s %s" % (*row,)

Use tuple:

row = [1, 2, 3, 4]
"%s %s %s %s" % tuple(row)

Or you list all parameters extra:

row = [1, 2, 3, 4]
"%s %s %s %s" % (row[0], row[1], row[2], row[3])
  • Related