在不引发跨数据库引用的情况下从 postgresql 中删除表未实现:使用 pandas/psycopg2

deleting tables from postgresql without raising cross-database references are not implemented: using pandas/psycopg2

我正在尝试从数据库中删除 table。 只要 name_Table 结构化为

schema.table

一切正常。但是,我在 public 架构中确实有一个 table。 当我尝试将其删除为:

public.subname.table

我得到这个答案:

cross-database references are not implemented: "public.subname.table"

如何删除public.subname.table

        print('Connecting to the PostgreSQL database...')
        postgresConnection = psycopg2.connect(
                    host=XXXXXX,
                    port=YYYYYYYYY,
                    database="mydb",
                    user=os.environ['user'],
                    password=os.environ['pwd'])

     
        cursor                = postgresConnection.cursor()
        dropTableStmt   = "drop TABLE %s;"%name_Table;

        # Create a table in PostgreSQL database
        print(dropTableStmt)
        cursor.execute(dropTableStmt)
        postgresConnection.commit()
        cursor.close();
        print('Database cursor closed.')
        postgresConnection.close()
        print('Database connection closed.')

public.subname.tablequote_ident(public.subname.table) 一样与 Identifier rules in that '.' is not a valid character. The way around that is to double quote the identifier e.g. "public.subname.table" or use the function quote_ident 发生冲突。在你的情况下 drop TABLE quote_ident(%s).

更新

以前的解决方案不是。我没有测试它,只是假设。经过测试的解决方案:

--In psql
create table "public.subname.table"(id int);

select * from "public.subname.table";
 id 
----
(0 rows)

--In Python
import psycopg2
from psycopg2 import sql 

con = psycopg2.connect(dbname="test", host='localhost', user='postgres') 

cur = con.cursor()
cur.execute(sql.SQL("DROP table {table}").format(table=sql.Identifier("public.subname.table")))
con.commit()

--psql
select * from "public.subname.table";
ERROR:  relation "public.subname.table" does not exist
LINE 1: select * from "public.subname.table";

这利用 psycopg2 sql 模块在查询字符串中正确安全地引用 table 名称。

DROP TABLE public."subname.table"随心所欲

sql.Identifier("public", "subname.table") 是你想要的 psycopg2 标识符。