psycopg2 - 更新 Json 列时如何转义单引号?



我正在尝试更新表的 json 列,但由于 json 中的一个值有一个单引号而卡住了。

我的 JSON 字符串看起来像这样

{"keyword": "women's shoes"}

这是我的代码。

criteria_str = json.dumps(criteria)
sql_str = """update user_saved_search_backup set criteria = '%s'::json where id = %d;""" % (criteria_str, id)                    
write_cursor.execute(sql_str)

注意:我正在使用缺乏json函数支持的postgreSQL 9.2,所以我不得不在python中执行此操作

任何帮助将不胜感激。

使用参数化查询。切勿直接将用户输入插入 SQL 查询中,这会使您面临 SQL 注入攻击。

喜欢这个:

sql_str = """update user_saved_search_backup set criteria = %s::json where id = %s;"""
write_cursor.execute(sql_str, (criteria_str, id))

以下是有关此主题的一些有用文档。

最新更新