我有一个名为properties
的字段的表格,其类型为jsonb
。像这样:
CREATE TABLE mytable
(
id integer NOT NULL,
...snip...
properties jsonb
)
我可以在pgAdmin中查询它,如下所示:
SELECT id from mytable where properties@>'{"favorites": [{"icecream": "vanilla"}]}';
现在我想用psycopg2来做,但我想参数化它。
通常,这可以这样做:
cursor.execute("SELECT id from mytable where something = (%s)", (123456))
你如何用jsonb做到这一点?然后你如何参数化冰淇淋的味道?
到目前为止,我已经走了多远。
import psycopg2
from psycopg2.extras import register_default_jsonb, register_default_json, Json
...snip...
register_default_jsonb()
register_default_json()
def who_likes_this_icecream(flavor):
#where_clause = '{"favorites": [{"icecream": "vanilla"}]}'
where_clause = Json({"favorites": [{"icecream": "vanilla"}]})
q = "SELECT id from mytable where properties @> (%s)"
with get_a_cursor() as cursor:
cursor.execute(q, (where_clause))
data = cursor.fetchone()
r = cursor.fetchone()
return r[0]['id']
id = who_likes_this_icecream('vanilla')
print (id)
我尝试在psycopg2中使用Json包装器并收到:
TypeError: 'Json' object does not support indexing
我尝试将JSON作为格式化字符串发送并收到:
TypeError: not all arguments converted during string formatting
此外,我不确定如何在不引入注入问题的情况下安全地发送变量flavor
。