首页 > 解决方案 > 将字典内容插入字符串以提取查询计划

问题描述

我正在使用 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 字符串中获取字典内容,最好是键及其值?

标签: pythonpostgresqlpsycopg2

解决方案


让 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"}'

推荐阅读