首页 > 解决方案 > 如何使用 psycopg2.sql.Identifier 作为单引号?

问题描述

创建使用 postgresql 数据库创建表的函数时出现错误

def create_table(tb_names, cursor):

cursor.execute(sql.SQL("DROP TABLE IF EXISTS {}").format(sql.Identifier(tb_names)))
cursor.execute(sql.SQL("""CREATE TABLE {}(
                        id SERIAL,
                        PRIMARY KEY (id))
                """).format(sql.Identifier(tb_names)))
cursor.execute(sql.SQL("SELECT AddGeometryColumn({}, 'geom', 3375, 'POLYGON', 2)").format(sql.Identifier(tb_names)))
cursor.execute(sql.SQL("CREATE INDEX geomIndex ON {} USING GIST 

(geom)").format(sql.Identifier(tb_names)))

create_table(tb_names="test_data1", cursor=cur)
error:
psycopg2.errors.UndefinedColumn: column "test_data1" does not exist
LINE 1: SELECT AddGeometryColumn("test_data1", 'geom', 3375, 'POLYGO...

知道如何解决吗?

如何将变量作为单引号传递?

对不起,我的英语不好

标签: pythonpostgresqlpsycopg2

解决方案


...将其作为常规参数传递给execute?

要点是当字符串是要在查询中注入的标识符时sql.Identifier应用标识符引用规则。这就是它在第一个、第二个和最后一个查询中的使用方式,但在第三个查询中它看起来是一个常规参数,为什么要引用并注入它作为标识符?


推荐阅读