簡體   English   中英

在psycopg2中將表名作為參數傳遞時,公共表不存在關系

[英]Passing table name as a parameter in psycopg2, relation does not exist for a public table

似乎在psycopg2中將表名作為參數傳遞對於外部公共表不起作用。 代碼和結果如下。不勝感激。

此代碼運行良好。 cursor.execute('select * from public.wc_test limit 1')

但是,此代碼返回一個錯誤cursor.execute(sql.SQL('select * from {} limit 1').format(sql.Identifier('public.wc_test')))

()中的ProgrammingError追溯(最近一次調用最后一次)----> 1 cursor.execute(sql.SQL('select * from {} limit 1')。format(sql.Identifier('public.wc_test'))) ProgrammingError:關系“ public.wc_test”不存在第1行:從“ public.wc_test”限制1中選擇*

這是代碼和輸出的屏幕截圖

新問題:

似乎我又用另一個表遇到了同樣的問題,即使我分離了模式和表名。 您有什么想法導致此錯誤嗎? 謝謝!

這是代碼和輸出的屏幕截圖

模式名稱和表名稱必須分別傳遞,否則它們將像在"public.wc_text"中應被加引號的"public"."wc_test"一樣被一起引用。 所以要么

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

要么

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

您可以為此使用AsIs postrgresql擴展方法:

適配器符合ISQLQuote協議,該協議對字符串表示形式已作為SQL表示形式有效的對象很有用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM