I would like to add some python-dictionary data in to dynamic mysql tables, but I'm stuck at line 12:
## INSERT DATA TO TABLE
for key,val in j_decoded["one-wire"].items():
try:
rom = key.encode('utf-8')
temperatuur = val["temperatuur"]
createsqltable = """CREATE TABLE IF NOT EXISTS `%s` (
id INT PRIMARY KEY AUTO_INCREMENT,
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
timestamp TIMESTAMP,
temp FLOAT)""" % (rom)
cursor.execute(createsqltable)
cursor.execute("""INSERT INTO %s (timestamp, temp) VALUES (%s,%s)""",(rom,timestampdata,temperatuur))
db.commit()
except:
db.rollback()
## CLOSE THE DATABASE
db.close()
The tables are created. But the data never makes it.
Before the above code, I had some other code which did work, but I wasn't happy about the tablenames. I've put some ` at line 10:
temp FLOAT)""" % (`rom`)
This created the table as 'tablename' instead of tablename
And I had the following change at line 12: (see the first `%s`)
cursor.execute("""INSERT INTO `%s` (timestamp, temp) VALUES (%s,%s)""",(rom,timestampdata,temperatuur))
Which added the data nicely into the 'tablename' table
Now I removed some ` and the table got created OK, but the data never makes it to the table. I've read a few posts from others, but I can't seem to fix it (I think I've tried all the ` ' " combinations)
And a merry Xmas to you :)
2014-01-04 I've changed the code to:
cursor.execute("""INSERT INTO {0} (timestamp, temp) VALUES (%s,%s)""".format(a), (b,c))