![](/img/trans.png)
[英]Psycopg2 INSERT query string composition with execute_values
[英]Query String Composition in Psycopg2
我正在尝试使用 Psycopg2 从 Python 在 Postgres 中运行 SQL“SELECT”查询。 我正在尝试编写如下查询字符串,但收到错误消息,使用 psycopg2 2.9 版。
from psycopg2 import sql
tablename = "mytab"
schema = "public"
query = sql.SQL("SELECT table_name from information_schema.tables where table_name = {tablename} and table_schema = {schema};")
query = query.format(tablename=sql.Identifier(tablename), schema=sql.Identifier(schema))
cursor.execute(query)
result = cursor.fetchone()[0]
错误:
psycopg2.error.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
有人可以帮忙吗。 谢谢。
在(有点奇怪)查询中
select table_name
from information_schema.tables
where table_name = 'mytab'
and table_schema = 'public';
'mytab'
和'public'
是文字,而不是标识符。 为了比较, mytab
是这里的标识符:
select *
from mytab;
因此,您的format
声明应如下所示:
query = query.format(tablename=sql.Literal(tablename), schema=sql.Literal(schema))
请注意,引用的错误消息有些误导,因为它是关于执行问题中显示的查询以外的查询。
由于此查询仅处理动态值,因此可以简化为:
import psycopg2
con = psycopg2.connect(<params>)
cursor = con.cursor()
tablename = "mytab"
schema = "public"
# Regular placeholders
query = """SELECT
table_name
from
information_schema.tables
where
table_name = %s and table_schema = %s"""
cursor.execute(query, [tablename, schema])
result = cursor.fetchone()[0]
# Named placeholders
query = """SELECT
table_name
from
information_schema.tables
where
table_name = %(table)s and table_schema = %(schema)s"""
cursor.execute(query, {"table": tablename, "schema": schema})
result = cursor.fetchone()[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.