1
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']
2
  • can i know the contents of final.csv Commented Nov 26, 2013 at 7:01
  • i updated the answer. you need data=row[0].split('\t') because it is not comma seperated, rather it is tab seperated Commented Nov 26, 2013 at 7:15

1 Answer 1

1
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)
Sign up to request clarification or add additional context in comments.

6 Comments

Already tried it, list index out of range error. I am updating question with csv content.
Nope, cursor.execute("insert into newsletter_subscriber(id, name, email) values (?, ?, ?)", (data[0], data[1], data[2])) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute` query = query % db.literal(args) TypeError: not all arguments converted during string formatting`
@user2032220 try (int(data[0]), data[1], data[2]))
@user2032220 i updated answer. i don't know what is the problem sorry :(
tried that which results in query="""insert into newsletter_subscriber(id, name, email) values(%d, '%s', '%s')""" %(int(data[0]), data[1], data[2]) IndexError: list index out of range `
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.