我正在使用PostgreSQL 12和Python 3.8。我想找出利用PostgreSQL中的JSON兼容性的方法。
我的问题是执行select语句时出现错误。为了触发索引,我需要使用运算符@>
,并且该运算符期望使用类似'{"age":"37"}'
的东西。我只是无法在查询字符串中找到这本词典...
我有下表:
create table json_table1 (
p_id int primary key,
first_name varchar(20),
last_name varchar(20),
p_attribute jsonb,
quote_content text
)
这是Python代码:
import psycopg2
from psycopg2.extras import RealDictCursor
import json
def main():
connection_string = " "
connection = psycopg2.connect(connection_string)
cursor = connection.cursor(cursor_factory=RealDictCursor)
cursor.execute("set search_path to public")
test_dict = {
'age':'37'
}
sql="explain analyze select * from json_table1 where p_attribute @> '{'age':%s}'"
cursor.execute(sql, (test_dict['age'],))
result = cursor.fetchall()
with open('with_gin.json', 'w') as output:
json.dump(result, output, indent=4)
if __name__ == "__main__":
main()
这是我的错误:
Traceback (most recent call last):
File "C:/PATH", line 27, in <module>
main()
File "C:/PATH", line 19, in main
cursor.execute(sql, (test_dict['age'],))
File "C:\PATH", line 243, in execute
return super(RealDictCursor, self).execute(query, vars)
psycopg2.errors.SyntaxError: syntax error at or near "age"
LINE 1: ...select * from json_table1 where p_attribute @> '{'age':'37'}...
此查询在pgAdmin4内部有效:
explain analyze select * from json_table1
where p_attribute @> '{"age":"37"}'
我希望动态插入字典内容,但首先需要使用静态字典。
如何在sql字符串中获取字典内容,最好是键及其值?
让psycopg2为您处理参数:
import json
...
sql="explain analyze select * from json_table1 where p_attribute @> %s"
cursor.execute(sql, (json.dumps(test_dict),))
print(cursor.mogrify(sql, (json.dumps(test_dict),)))
输出:
explain analyze select * from json_table1 where p_attribute @> '{"age": "37"}'