【问题标题】:insert json into mysql. json string is obtained from json.dumps将json插入mysql。 json 字符串是从 json.dumps 中获取的
【发布时间】:2012-07-14 22:25:54
【问题描述】:

问题在于将 json 字符串插入 MySQL 数据库。 在我的 python 程序中,我获得了 json 作为json.dumps(d) 的结果,其中 d 是字典。插入代码是:

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

看起来问题是引号,引号前没有转义符号。 我该如何解决这个问题?

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

    在进行查询时使用参数化方法来处理值。驱动程序将处理转义:

    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\"}
    

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多