简体   繁体   English

在 Psycopg2 中查询字符串组合

[英]Query String Composition in Psycopg2

I am trying to run a SQL "SELECT" query in Postgres from Python using Psycopg2.我正在尝试使用 Psycopg2 从 Python 在 Postgres 中运行 SQL“SELECT”查询。 I am trying to compose the query string as below, but getting error message, using psycopg2 version 2.9.我正在尝试编写如下查询字符串,但收到错误消息,使用 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]

Error:错误:

psycopg2.error.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block

Can someone please help.有人可以帮忙吗。 Thanks.谢谢。

In the (a bit strange) query在(有点奇怪)查询中

select table_name 
from information_schema.tables 
where table_name = 'mytab'
and table_schema = 'public';

'mytab' and 'public' are literals, not identifiers. 'mytab''public'是文字,而不是标识符。 For comparison, mytab is an identifier here:为了比较, mytab是这里的标识符:

select *
from mytab;

Thus your format statement should look like this:因此,您的format声明应如下所示:

query = query.format(tablename=sql.Literal(tablename), schema=sql.Literal(schema))

Note that the quoted error message is somewhat misleading as it is about executing a query other than what is shown in the question.请注意,引用的错误消息有些误导,因为它是关于执行问题中显示的查询以外的查询。

Since this query is only dealing with dynamic values it can be simplified to:由于此查询仅处理动态值,因此可以简化为:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM