python - 将字典内容插入字符串以提取查询计划
问题描述
我正在使用 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"}'
推荐阅读
- arrays - BigQuery:使用 UNNEST 检查数组的内容
- python - 如何用python复制字符串中的字符(就地)?
- windows - App-V 虚拟进程和本地文件系统?
- npm - 如何在内置 Webstorm 终端中使用 snyk 命令
- java - 将列表转换为地图
- logic - 用 OR 和 NOT 创建 AND 表达式
- angular - 使用 JEST 运行 Angular 组件测试给出了找不到模块
- themes - PhpStorm 更改单元测试工具栏颜色
- javascript - 表的 SAPUI5 数据绑定不起作用
- bash - 如何使用 sed 替换“word{word”或“word}word”