pynovice
pynovice

Reputation: 7752

Not enough argument for format string while importing csv into MySQL database

Full Traceback:
 File "./csvimportdb.py", line 12, in <module>
    cursor.execute('''INSERT INTO newsletter_subscriber(id, name, email ) VALUES("%s", "%s", "%s")''', row)
  File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 159, in execute
    query = query % db.literal(args)
TypeError: not enough arguments for format string

My Code:

#!/usr/bin/python

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost', user='english', passwd='english', db='english_mez')
cursor = mydb.cursor()

csv_data = csv.reader(file('final.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO newsletter_subscriber(id, name, email )' 'VALUES("%s", "%s", "%s")', row[0], row[1], row[2])
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

I need to pass row, row, row to make it right but can't do that. How to fix?

Edit: Printing row gives:

['6630\tCarmen Rocche\[email protected]\t\t\t\t\t']
['6631\tSuhasini\[email protected]\t\t\t\t\t']
['6632\tAmarjeet \[email protected]\t\t\t\t\t']
['6633\tFazali Hadi\[email protected]\t\t\t\t\t']
['6634\tVishaka Samarakone\[email protected]\t\t\t\t\t']
['6635\tLoemongga\[email protected]\t\t\t\t\t']

Upvotes: 1

Views: 2051

Answers (1)

suhailvs
suhailvs

Reputation: 21690

for row in csv_data:
    data=row[0].split('\t')
    if len(data) < 4: continue
    query="""insert into newsletter_subscriber (id, name, email) values 
      (%d, '%s', '%s')""" %(int(data[0]), data[1], data[2])
    cursor.execute(query)

Upvotes: 1

Related Questions