1

The problem is with inserting json strings into MySQL database. In my python program I obtain json as a result of json.dumps(d) where d is a dictionary. Inserting code is:

        query = ("INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"%
                 (article_id, revision_number, jsn))
        print query
        cur.execute(query)

It looks like the problem is quotes, there is no escape symbol in front of quotes. How can I fix this?

1 Answer 1

4

Use the parameterized approach to values when doing a query. The driver will handle escapes:

query = "INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"
cur.execute(query, (article_id, revision_number, jsn))

If you want direct and manual access to the escape function MySQLdb uses, you can do it like this:

c = MySQLdb.connection()
print c.escape_string('{"foo":"bar"}')
# {\"foo\":\"bar\"}
Sign up to request clarification or add additional context in comments.

Comments

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.