-1

I'm attempting to post data to a table where the name of the table is a variable, i receive no errors, however no data is posting.

cursor = db.cursor()
cursor.execute('DROP TABLE IF EXISTS %s' %data[1])

0L

sql ="""CREATE TABLE %s  (IP TEXT, AVAILIBILITY INT)""" %data[1]
cursor.execute(sql)
0L

for key in data[0]:
    print type(key), type(data[0][key])
    sql = """INSERT INTO %s VALUES (%s,%s)""" %(data[1],key,data[0][key])
RayGunV
  • 17
  • 6
  • 1
    Related and probably a duplicate: [Python MySQLdb execute table variable](http://stackoverflow.com/questions/15255694/python-mysqldb-execute-table-variable). – alecxe May 13 '15 at 13:21
  • do you `db.commit()`? – Matthew May 13 '15 at 13:30
  • You're right, i wasn't using db.commit() That made the runtime take longer and i thought it would work but it's still not posting – RayGunV May 13 '15 at 13:34

1 Answers1

0

Your code never executes the INSERT statement; it only defines a string sql. You'll need to add a cursor.execute call inside the loop.

You should also be parameterizing your query as much as possible, even when you can't parameterize some part (like a table or column name). I recommend using advanced string formatting here to avoid having to escape your parameterization placeholders.

If you had written it this way to begin with, you might have noticed the missing line more easily:

for key in data[0]:
    sql = 'INSERT INTO {} VALUES (%s,%s)'.format(data[1])  # can't supply object names
    cursor.execute(sql, (key, data[0][key]))               # as parameters, but values ok
Air
  • 8,274
  • 2
  • 53
  • 88