简体   繁体   中英

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

It seems like passing table name as a parameter in psycopg2 doesn't work for an outside public table. The code and result as below.Appreciate any helps.

This code works well. cursor.execute('select * from public.wc_test limit 1')

However, this code returns an error cursor.execute(sql.SQL('select * from {} limit 1').format(sql.Identifier('public.wc_test')))

ProgrammingError Traceback (most recent call last) in () ----> 1 cursor.execute(sql.SQL('select * from {} limit 1').format(sql.Identifier('public.wc_test'))) ProgrammingError: relation "public.wc_test" does not exist LINE 1: select * from "public.wc_test" limit 1

Here is the screenshot of the code and output

New Issue:

It seems I got the same issue again with another table, even I separated the schema and the table name. Do you have any ideas what results in this error? Thanks!

Here is the screenshot of the code and the output

The schema and table name must be passed separately otherwise they will finish being quoted together like in "public.wc_text" where it should be "public"."wc_test" . So either

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

or

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

You can use AsIs postrgresql extension method for this:

Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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