1

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.?

2
  • 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. Commented Sep 25, 2013 at 4:43
  • Read: stackoverflow.com/questions/8519599/… Commented Sep 25, 2013 at 4:43

2 Answers 2

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[...])
Sign up to request clarification or add additional context in comments.

1 Comment

@GrijeshChauhan - Yes I knew it before. For complete explanation, refer to another answer provide.
1

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

Yaa I know. That is my concern. How do I store the full dictionary with quotes in DB?
Please read answers and seralize/deserialize your dict from and to JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.