将json插入到mysql中。 json字符串从json.dumps获取
问题描述:
问题是将json字符串插入MySQL数据库。 在我的python程序中,我获得了json,作为json.dumps(d)
的结果,其中d是一个字典。插入代码是:将json插入到mysql中。 json字符串从json.dumps获取
query = ("INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"%
(article_id, revision_number, jsn))
print query
cur.execute(query)
它看起来像问题是引号,引号前面没有转义符号。 我该如何解决这个问题?
答
执行查询时,使用参数化的方法处理值。该驱动程序将处理转义:
query = "INSERT INTO bm_triesJsons VALUES (%s, %s, %s);"
cur.execute(query, (article_id, revision_number, jsn))
如果你想逃生功能MySQLdb的使用直接和手动连接,你可以做这样的:
c = MySQLdb.connection()
print c.escape_string('{"foo":"bar"}')
# {\"foo\":\"bar\"}