Python 在psycopg2中将表名作为参数传递,公共表的关系不存在

Python 在psycopg2中将表名作为参数传递,公共表的关系不存在,python,postgresql,parameter-passing,psycopg2,Python,Postgresql,Parameter Passing,Psycopg2,似乎在psycopg2中将表名作为参数传递对于外部公共表不起作用。代码和结果如下。感谢您的帮助 这段代码运行良好。 cursor.execute('select*from public.wc_test limit 1') 但是,此代码返回一个错误 cursor.execute(sql.sql('select*from{}limit 1').format(sql.Identifier('public.wc_test'))) 编程错误回溯(最近一次调用上次) 在() ---->1 cursor.ex

似乎在psycopg2中将表名作为参数传递对于外部公共表不起作用。代码和结果如下。感谢您的帮助

这段代码运行良好。
cursor.execute('select*from public.wc_test limit 1')

但是,此代码返回一个错误
cursor.execute(sql.sql('select*from{}limit 1').format(sql.Identifier('public.wc_test')))

编程错误回溯(最近一次调用上次) 在() ---->1 cursor.execute(sql.sql('select*from{}limit 1')。格式(sql.Identifier('public.wc_test')) 编程错误:关系“public.wc_test”不存在 第1行:从“public.wc_测试”限制1中选择*

新发行:

似乎我在另一个表中又遇到了同样的问题,甚至我将模式和表名分开了。你知道是什么导致了这个错误吗?谢谢


必须单独传递架构和表名,否则它们将像在
中的“public.wc\u text”
中的“public”;“wc\u test”中一样被一起引用。所以

cursor.execute(
    sql.SQL('select * from public.{} limit 1').format(
        sql.Identifier('wc_test')
    )
)

您可以为此使用postrgresql扩展方法:

适配器符合ISQLQuote协议,对于字符串表示形式已经作为SQL表示形式有效的对象非常有用


您需要在
str
上执行
.format
,而不是
SQL
对象:cursor.execute(SQL.SQL('select*from{}limit 1')。format(SQL.Identifier('public.wc_test'))@bow应该是一个很有意义的答案。它工作得很好。非常感谢你!您好,您的解决方案很有效,但当我使用桌子时,我又遇到了同样的问题。你能帮我再检查一下吗?我在“新发行”下面增加了更多细节?你知道我这次为什么会有这个问题吗?如果你需要更多的信息,请告诉我。非常感谢你!你能查一下上面的评论吗?谢谢大家!@Clodoaldo@WenqiCheng发布另一个带有确切代码的问题。
cursor.execute(
    sql.SQL('select * from {}.{} limit 1').format(
        sql.Identifier('public'),
        sql.Identifier('wc_test')
    )
)
import psycopg2
from psycopg2.extensions import AsIs

QUERY = 'SELECT * from %(table)s limit 1'

data = {'table': AsIs('public.wc_test')}

with conn.cursor() as cursor:
    cursor.execute(QUERY, data)
    rows = cursor.fetchall()        
return rows