简体   繁体   中英

Unable to insert CSV in MySQL using Python3

I have a CSV file that has the following lines:

10472;141507 some text.;810, smoe more text;city; 99,0060198416; -99,3360490152;some(a)textène, moretextèse;additional text s * (topl), again again text*;R : No retée;2015-02-03;

What I am trying to achieve is to insert the values delimited by a ; into a table.

import csv
from dbconnect import connection
import codecs

cursor, conn = connection()

sql = """
INSERT INTO mddelcc
  (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
VALUES
  (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
"""

with codecs.open('file.csv', 'rb', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile, delimiter = ';', quoting=csv.QUOTE_NONE)
    for row in reader:
        cursor.execute(sql,row)
conn.commit()
cursor.close()
print("Done")

When running the code, I receive the following error:

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting

Can someone please point me in the right direction ?

You have 10 fields in your string but 11 values.

Change sql to this:

sql = """
INSERT INTO mddelcc
  (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10)
VALUES
  (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
"""

or to this

sql = """
INSERT INTO mddelcc
  (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10,field11)
VALUES
  (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
"""

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