【问题标题】:drop postgreSQL table with Quotation Marks in name using psycopg2使用 psycopg2 删除名称中带有引号的 postgreSQL 表
【发布时间】:2022-01-15 20:19:52
【问题描述】:

我在架构中有一个表。

my_schema.my_table

在同一个模式中,我还有一个表名相同但带引号

my_schema."my_table"

如何使用 psycopg2 删除 my_schema."my_table"? (不要冒险放弃my_schema.my_table

我试过了:

postgresConnection = psycopg2.connect(...)
from psycopg2 import sql 

cursor                = postgresConnection.cursor()
name_Table            = 'my_schema."my_table"'
cursor                = postgresConnection.cursor()
dropTableStmt   = "drop TABLE %s;"%name_Table;
cursor.execute(dropTableStmt)
postgresConnection.commit()
cursor.close();

但我明白了

SyntaxError: zero-length delimited identifier at or near """"
LINE 1: drop TABLE my_schema.""my_table"";

我也试过了:

from psycopg2 import sql 

cursor                = postgresConnection.cursor()
name_Table            = 'my_schema.""my_table""'
cur = postgresConnection.cursor()
cur.execute(sql.SQL("DROP table {table}").format(table=sql.Identifier(name_Table)))
postgresConnection.commit()
cursor.close();

然后我得到:

UndefinedTable: table "my_schema.""my_table""" does not exist

【问题讨论】:

  • my_table 与“my_table”相同,如果它们位于相同的模式中。在psql\dt my_schema.* 确认。
  • 关于sql.SQL 中的错误,请参阅sql class psycopg2.sql.Identifiersql.Identifier("schema", "table")
  • 出于某种原因,它们是不同的表。你的第二条评论解决了,你能回答一下吗?
  • 那么my_schema.my_table 还存在吗?如果是这样,名称中必须有某种隐藏字符。如果你这样做 select * from pg_class where relname = 'my_table'; 会发生什么?

标签: python postgresql character-encoding psycopg2


【解决方案1】:

要对对象名称中的双引号进行转义,请使用双引号:

DROP TABLE my_schema."""my_table""";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2022-12-20
    相关资源
    最近更新 更多