0

I have adapted this code (posted below to save you the click) to work for me. I have two questions.

1) how do I get the uploader to skip the header row? Right now it will upload the first row out of my CSV which just defines the columns. So an entry into my DB will be "First Name, Last Name, Email" in this example.

2) 2 columns read "First Name" "Last Name" and apparently that space screws it up throwing an error saying there is a problem with my SQL syntax and to check the manual for my version. After playing around with it on my own I found that if I replaced the space with an _ and it worked. So the new column was "First_Name" and "Last_Name". Is there a way to not get the error and also not use the underscore?

import csv
import MySQLdb

mydb = MySQLdb.connect(host='server IP',
    user='DB User Name',
    passwd='PW for DB user',
    db='name of DB')
cursor = mydb.cursor()

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

    cursor.execute('INSERT INTO testcsv(First_Name, \
          Last_Name,email )' \
          'VALUES("%s","%s","%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
Community
  • 1
  • 1
Mxracer888
  • 341
  • 1
  • 4
  • 14

1 Answers1

2

To skip the first row, could just use:

next(csv_data, None)    
for row in csv_data:

I don't think mysql accepts column names with spaces, so underscores sound like a reasonable workaround, you can still display differently to a user.

Stefan
  • 41,759
  • 13
  • 76
  • 81
  • so just add the [1:] part in? I tried that and it says "TypeError: '_csv.reader' object has no attribute '___getitem___' – Mxracer888 Dec 01 '15 at 19:03
  • I don't know why that is going bold on me, it should be two underscores and then 'getitem' and then two more underscores. – Mxracer888 Dec 01 '15 at 19:04
  • Updated my answer, that was actually the wrong way to skip for the object returned by `csv.reader`. `next` skips a single line, in this case the first. – Stefan Dec 01 '15 at 19:11