Python-psycopg2.sql –调用函数

我尝试在动态SQL中调用子字符串函数。

from psycopg2 import sql as ps_sql

sql = ps_sql.SQL('select {}').format(ps_sql.Identifier("substring('TEST',1,2)"))
with db.conn_ogis.cursor() as cursor:
    cursor.execute(sql)

我有错误:psycopg2.errors.UndefinedColumn:错误:列“ substring('TEST',1,2)”不存在

如何正确调用函数?

zhenyuting 回答:Python-psycopg2.sql –调用函数

仅将Identifier()函数用于Postgres标识符(即表,列,视图,函数等的名称)。因此,您可以通过以下方式使用它:

sql = ps_sql.SQL("select {}('TEST',1,2)").format(ps_sql.Identifier("substring"))

实际上,在这种情况下,标识符substring不需要引用(因为它是小写的):

sql = ps_sql.SQL("select substring('TEST',2)")
本文链接:https://www.f2er.com/3159718.html

大家都在问