0

I'm writing a python script for inserting a csv file into a mysql table. The problem I am having is that it is only inserting one line and terminating after that.

#!/usr/bin/python

import sys
import csv 
import MySQLdb

db = MySQLdb.connect(host="localhost",user="root",passwd="password",db="AM")
cur = db.cursor()


f = open(sys.argv[1],'rt')
try:
    reader = csv.reader(f)
    headers = next(reader)
    for row in reader:
        col1 = row[0]
        col2 = row[1]
        col3 = row[2]
        col4 = row[3]
        col5 = row[4]
        col6 = row[5]
except:
     print sys.exc_info()


sql = "Insert ignore into my_table(col1, col2, col3, col4, col5, col6) values ('%s', '%s', '%s', '%s', '%s', '%s');" % (col1, col2, col3, col4, col5, col6)
try:
    cur.execute(sql)
    db.commit()
except:
    db.rollback()
finally:
    db.close() 

1 Answer 1

-1
sql = "Insert ignore into table(a,b,c,d,e,f) values ('%s', '%s', '%c', '%s', '%s', '%s');" % (list1, list2, list3, list4, list5, list6)

Is your table actually named "table"? If so, you should surround it in double quotes like so:

sql = "Insert ignore into \"table\"(a,b,c,d,e,f) values ('%s', '%s', '%c', '%s', '%s', '%s');" % (list1, list2, list3, list4, list5, list6)

table is a SQL keyword.

3
  • The problem seems to lie in my string formatting. Surrounding my table name with double quotes produces another Syntax error at values. Commented Sep 8, 2014 at 16:23
  • Try adding space after \"table\" ie \"table\" (a,b,c,d,e,f). Are your columns actually named a,b,c,d,e,f? Commented Sep 8, 2014 at 17:03
  • It turns out that the problem was because I forgot to add in except. Now I am encountering a different problem. Thanks for your help! Commented Sep 10, 2014 at 18:27

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.