I want to insert a dictionary a = {'key': 602L} into DB in python. It does not allows me to insert it because of the quotes'' in key.
Here is my query
self.__db_conn.cursor.execute("INSERT INTO TABLE VALUES ('%s')" % (str(a)))
If I manually try to insert it(without quotes), it does work.
self.__db_conn.cursor.execute("INSERT INTO TABLE VALUES ('%s')" % ("{key: 602L}"))
Note the missing quotes in key.
How do I insert a dictionary into a table.?
-
Why do you want to store a dict this way into a database? In doubt: serialize or deserialize using JSON a dict to a string and back but not this way.user2665694– user26656942013年09月25日 04:43:42 +00:00Commented Sep 25, 2013 at 4:43
-
Read: stackoverflow.com/questions/8519599/…Grijesh Chauhan– Grijesh Chauhan2013年09月25日 04:43:46 +00:00Commented Sep 25, 2013 at 4:43
2 Answers 2
Serialize to JSON
self.__db_conn.cursor.execute("INSERT INTO TABLE VALUES ('%s')" % json.dumps(your_dict)
Unserialize from JSON
row = db.conn.fetchone(.....)
your_dict = json.loads(row[...])
1 Comment
str(a) is "{'key': 602L}". Replacing this into the SQL statement gives:
INSERT INTO TABLE VALUES ('{'key': 602L}')
Note the mismatch of single quotes. Look into escaping the single quotes.
EDIT
As user2799617 mentioned, you can try the following:
import json
a_json = json.dumps(str(a))
self.__db_conn.cursor.execute("INSERT INTO TABLE VALUES ('%s')" % a_json)
When you get the value back from the database, you can use json.loads.
2 Comments
with quotes in DB?