gpt4 book ai didi

python - 使用 psycopg2 编写动态 SQL 字符串

转载 作者:行者123 更新时间:2023-11-29 12:02:56 24 4
gpt4 key购买 nike

我在 python (2.7.10) 中使用 psycopg2 连接到 postgresql 数据库。文档对动态 SQL 语句的组成非常清楚:

Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

psycopg2 2.7 版中,有新的 sql 模块可以安全地防止 SQL 注入(inject)来执行此字符串组合。尽管如此,我还是不明白如何正确构建如下语句:

import psycopg2 as ps

C = psycopg.connect(host='my_host', port=Port, database='My_DB')
cur = C.cursor()
schema = 'some_schema'
table = 'some_table'
SQL = cur.execute("SELECT * FROM "+schema+"."+table+";") # This is horribly wrong
SQL = cur.execute("SELECT * FROM some_schema.some_table;") # That's what the result should be

最佳答案

您可以使用 psycopg2.sql.Identifier将标识符插入查询,例如:

from psycopg2.sql import Identifier, SQL

query = SQL('SELECT * FROM {}.{}').format(*map(Identifier, (schema, table)))
print(query.as_string(conn))
cur.execute(query)

根据链接的文档页面,在 psycopg2 v2.8+ 中,您还可以将多个字符串传递给 Identifier 以表示限定名称,即以点分隔的序列标识符:

query = SQL('SELECT * FROM {}').format(Identifier(schema, table))

关于python - 使用 psycopg2 编写动态 SQL 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46770201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com