简体   繁体   中英

postgresql ProgrammingError: function identifier(unknown) does not exist

I'm trying to use psycopg2.sql.SQL to compose my query. I've referred to the docs but I'm unable to get this to execute. I keep getting the above programming error

Here's the example code:

import psycopg2.sql as sql

query = sql.SQL("SELECT id from {} where country={}".format(sql.Identifier('country_sector'), sql.Identifier('UK')))

cur = dbobj.conn.cursor()
cur.execute(query)
data = cur.fetchall()

And here is the error:

ProgrammingError: function identifier(unknown) does not exist
LINE 1: SELECT id from Identifier('country_sector') where country=Id...
                       ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

This suggests to me that I need to install some extension in postgres but a lot of googling has not helped.

Any advice much appreciated.

You're using the format() wrongly. This works

import psycopg2
import psycopg2.sql as sql
conn=psycopg2.connect("dbname='mydb' user='myuser' ")
cur = conn.cursor()
cur.execute(
sql.SQL("SELECT id from {} 
        where country=%s").format(sql.Identifier('country_sector')),
['UK']
)
data = cur.fetchall()

I had the same issue, this solution might help.

The main takeaway is that you should use the psycopg2.sql.format() for the formatting of all named literals.

For table identifiers, note that in version 2.7.7, sql.Identifier() only accepts a single argument (multiple string args was added in 2.8). If you are using 2.7.7, you should format you sql template like so:

template = "SELECT * FROM {schema}.{table} WHERE date BETWEEN {ds} and {de}"
params = {
    "schema": sql.Identifier("myschema"),
    "table": sql.Identifier("mytable"),
    "ds": sql.Literal("2019-09-01"),
    "de": sql.Literal("2019-10-01")
}
query = sql.SQL(template).format(**params)

If you do it correctly, type(query) should be <class 'psycopg2.sql.Composed'>

My understanding is that the vars param in execute is mainly intended to pass in values for INSERT, etc. Hope this helps!

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