python - 如何使用 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...
知道如何解决吗?
如何将变量作为单引号传递?
对不起,我的英语不好
解决方案
...将其作为常规参数传递给execute
?
要点是当字符串是要在查询中注入的标识符时sql.Identifier
应用标识符引用规则。这就是它在第一个、第二个和最后一个查询中的使用方式,但在第三个查询中它看起来是一个常规参数,为什么要引用并注入它作为标识符?
推荐阅读
- python - 使用 matplotlib.widgets 中的 Slider 后如何获取条形图值?
- android - Xamarin android 存档失败
- php - echo 在页面源中而不是在页面上显示输出
- rest - 补丁 api 应该如何处理部分正确和部分不正确的数据?
- css - 移动端的响应式元素布局
- reactjs - If 语句中的 React 动画不呈现
- riscv - 为什么我可以在 Intel i5 上执行静态链接的 riscv helloworld 程序?我正在运行 Debian 测试
- rest - 如何使用linkedin API上传视频和发布?
- java - 单元测试模拟服务实现
- javascript - 使用 javascript Regex 解析 .gitmodules 文件以获取分支、路径、url