decoding JSON-string and insert in SQL-database (sqlite3)

Question:

I want to decode a JSON-formated string and insert it in a SQL-database via MySQL.

import json
import MySQLdb as mdb

my_json = '{"timestamp":1479132183,"sn":"B59EC63F","u":[3346,3346,3347,3346],"soc":96,"i":-32,"cc":345351,"ccMax":360000}'

parsed_stuff = json.loads(my_json)

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()

It throws the error:

"Unknown column ‘B59EC63F’ in ‘field list’"

Additionally throws

"IndexError: string index out of range".

Asked By: Bueddi

||

Answers:

I changed

VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)

to

VALUES (%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s)

and it works now.

Answered By: Bueddi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.