1

I've been fighting with this python code for a while and getting various errors when I try to execute.

import csv
import MySQLdb
# open the connection to the MySQL server.
# using MySQLdb
mydb = MySQLdb.connect(host='myhostinfo',
user='me',
passwd='mypw',
db='thedatabase')
cursor = mydb.cursor()
# read the presidents.csv file using the python
# csv module http://docs.python.org/library/csv.html
csv_data = csv.reader(file('CHN-mod.csv'))
# execute the for clicle and insert the csv into the
# database.
for row in csv_data:

    cursor.execute('INSERT INTO INDICATORS(INDICATORNAME, \
            , INDICATORCODE)' \
            'VALUES(%s, %s)',  row)
#close the connection to the database.
cursor.close()
print "Import to MySQL is over"

My code validates in an online python validator, but I'm getting errors:

Traceback (most recent call last):
  File "importdata.py", line 23, in <module>
    'VALUES(%s, %s)' , row)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 201, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaultterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' INDICATORCODE)VALUES('Indicator Name', 'Indicator Code'>' at line 1")

1 Answer 1

1
In [1]: 'INSERT INTO INDICATORS(INDICATORNAME, \
            , INDICATORCODE)' \
            'VALUES(%s, %s)'
Out[1]: 'INSERT INTO INDICATORS(INDICATORNAME,             , INDICATORCODE)VALUES(%s, %s)'

There are two commas after INDICATORNAME.


Use a multiline string instead:

cursor.execute('''INSERT INTO INDICATORS (INDICATORNAME, INDICATORCODE)
                  VALUES (%s, %s)''', row)

It is much easier to read and will avoid the problem you ran into. MySQLdb parses the string (despite the whitespaces) just fine.


To insert parts of each row to three different tables, you could do something like this:

insert_indicators = '''INSERT INTO INDICATORS (INDICATORNAME, INDICATORCODE)
                       VALUES (%s, %s)'''
insert_foo = 'INSERT INTO FOO (...) VALUES (%s)' % (','.join(['%s']*10))
insert_bar = 'INSERT INTO BAR (...) VALUES (%s)' % (','.join(['%s']*10))

for row in csv_data:
    cursor.execute(insert_indicators, row[:2])
    cursor.execute(insert_foo, row[2:12])
    cursor.execute(insert_bar, row[12:22])
1
  • I have a csv file with many columns and I want to import two to one table, ten to another, and ten to another still. How could I modify the code to be selective like that?
    – Tylerppp
    May 27, 2013 at 15:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.