簡體   English   中英

Python + Postgres + psycopg2:編寫動態json查詢並處理引號

[英]Python + Postgres + psycopg2 : Composing a dynamic json query and dealing with quotes

我正在嘗試使用Python和psycopg2驅動程序編寫一個涉及Postgres中json列的動態查詢。

where_clause = ''
parameters = []

for key, v in (arguments):
    parameters.append(key)
    parameters.append(v)
    where_clause = where_clause + "data @> '{\"%s\":%s}' AND "

sql = u'select * from my_table where ' + where_clause + ' 1 = 1
db = connect(connection_string)
cur = db.cursor()
cur.execute(sql, tuple(parameters))
rows = cur.fetchall()
cur.close()
db.close()

當我這樣做時,它有'{\\"%s\\":%s}'

psycopg2.ProgrammingError: syntax error at or near "favorite_topping"
LINE 1: select * from my_table where data @> '{"'favorite_topping'":'pepperoni'...

它不喜歡我如何安排報價。

問題似乎是psycopg2在組成最終查詢時如何選擇插入引號。

更新

如果我這樣做: where_clause = where_clause + "data @> \\"{%s:%s}\\" AND "

我得到的是這個:

where data @> "{'favorite_topping':'pepperoni'}"

而失敗是因為Postgres想要的是引用是相反的,如下所示:

where data @> '{"favorite_topping":"pepperoni"}'

有沒有辦法讓這種情況發生?

這是查詢參數化的工作方式 - 數據庫驅動程序將查詢參數的類型確定為字符串,並自動在轉義值周圍放置引號。

您可以使用常規字符串格式來解決此問題,但請確保自己驗證/清理/轉義查詢參數以避免SQL注入攻擊和平衡引號問題。

這應該可以解決您的問題:

from psycopg2.extras import Json
from psycopg2.extras import register_default_json
register_default_json(loads=lambda x: x)

query = u'select * from my_table where data @> %s;'
cur.execute(sql, Json({'favorite_topping':'pepperoni'})

主要基於https://github.com/psycopg/psycopg2/issues/190中的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM