简体   繁体   中英

Importing CSV into database using Python

I'm trying to import a csv file into a connecting MySQL database using python. However, I keep getting the following error: ProgrammingError: not enough arguments for format string.

All code runs perfect until: "cursor.execute(" Does anybody have any ideas?

Code used:

#Python connect with SQL
import MySQLdb
import csv
import sys

conn = MySQLdb.connect(host="127.0.0.1", user="root", password="", database="furniture")

print ("Connected with database")

cursor = conn.cursor()
csv_data = csv.reader(open(r"C:\Users\M.schuurman\Downloads\furniture2.csv"))
header = next(csv_data)

print('Importing the CSV Files')

for row in csv_data:
    print(row)
    cursor.execute(
        "INSERT INTO customer (customerid, customername, pcnumbers, pcletters, street,  number, province) VALUES (%s, %s, %s, %s, %s, %s, %s)", row)

conn.commit()
cursor.close()
print('Done')

Check the values of csv_data variable with print(list(csv_data)) or better with print(repr(row)) if csv_data is an iterator or the dataset is large.

As mentioned in the comment, the row does not have enough values to fill the %s placeholders of execute() function and will fail.

Here's more details on what's happening - the mysqlclient 's cursors.BaseCursor.execute() attempts a "templated string %s, %s" % ("one value", ) which will raise a TypeError that gets renamed into ProgrammingError .

>>> "templated string %s, %s" % ("one value", )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

and due to the count of placeholders ( %s ) being greater than the count of values for formating/templating the TypeError is raised.

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