0
我想解碼JSON格式的字符串並通過MySQL將其插入到SQL數據庫中。解碼JSON字符串並在SQL數據庫中插入(sqlite3)
import json
import MySQLdb as mdb
jsonofabitch = '{"timestamp":1479132183,"sn":"B59EC63F","u":[3346,3346,3347,3346],"soc":96,"i":-32,"cc":345351,"ccMax":360000}'
parsed_stuff = json.loads (jsonofabitch)
con = None
try:
con = mdb.connect('localhost', 'name', 'password', 'mysql')
cur = con.cursor()
cur.execute("SELECT * FROM database")
cur.execute("INSERT INTO database (timestamp, sn, u0, u1, u2, u3, soc, i, cc, ccMax) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (parsed_stuff['timestamp'], parsed_stuff['sn'], parsed_stuff['u'[1]], parsed_stuff['u'[2]], parsed_stuff['u'[3]], parsed_stuff['u'[4]], parsed_stuff['soc'], parsed_stuff['i'], parsed_stuff['cc'], parsed_stuff['ccMax']))
con.commit()
except mdb.Error as e:
print("Error %d: %s" % (e.args[0], e.args[1]))
sys.exit(1)
if con:
con.close()
它引發錯誤:
"Unknown column 'B59EC63F' in 'field list'"
此外拋出
"IndexError: string index out of range".
由於「parsed_stuff ['u'[1]]」,它拋出「IndexError」。當然是 – Bueddi
:它應該是'parsed_stuff ['u'] [1]'。 –
謝謝,它的工作原理! – Bueddi