Python 如何使用psycopg2将json传递给参数化sql语句? 将json传递到参数化SQL语句的正确语法是什么 如何将变量安全地传递到json中
我有一个表,其中有一个名为Python 如何使用psycopg2将json传递给参数化sql语句? 将json传递到参数化SQL语句的正确语法是什么 如何将变量安全地传递到json中,python,json,postgresql,psycopg2,jsonb,Python,Json,Postgresql,Psycopg2,Jsonb,我有一个表,其中有一个名为properties的字段,它被键入为jsonb。大概是这样的: CREATE TABLE mytable ( id integer NOT NULL, ...snip... properties jsonb ) 我可以在pgAdmin中查询它,如下所示: SELECT id from mytable where properties@>'{"favorites": [{"icecream": "vanilla"}]}'; 现在我想用psycopg
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'对象不支持索引
我尝试以格式化字符串的形式发送JSON,并收到:
TypeError:在字符串格式化过程中并非所有参数都已转换
另外,我不知道如何在不引入注入问题的情况下安全地发送变量flavor
我认为SQL中的括号是不必要的
“从…where properties@>%s中选择id”
光标。执行(q,(where\u子句,)
-where\u子句.Doh后加逗号。我看到了。后面的逗号表示元组。感谢@AbelistoHow将冰淇淋的味道参数化,以避免某种注射攻击。使用JSON可以吗?有什么例子吗?那么在JSON where子句上做一个字符串替换就足够了?我认为SQL中的括号不是必需的“从…where properties@>%s中选择id”
光标。执行(q,(where\u子句,)
-where\u子句.Doh后加逗号。我看到了。后面的逗号表示元组。感谢@AbelistoHow将冰淇淋的味道参数化,以避免某种注射攻击。使用JSON可以吗?有什么例子吗?那么在JSON where子句上做一个字符串替换就足够了?