【问题标题】:deleting tables from postgresql without raising cross-database references are not implemented: using pandas/psycopg2未实现从 postgresql 中删除表而不提高跨数据库引用:使用 pandas/psycopg2
【发布时间】:2021-11-24 23:56:12
【问题描述】:

我正在尝试从数据库中删除一个表。 只要name_Table 的结构为

schema.table

这一切都很好。但是,我在public 架构中确实有一张表。 当我尝试将其删除为:

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.table 这样的东西。有一个public 模式,其中可以有表,所以你可以有public.table。同样出于Parameters 此处显示的原因,您不想使用 `dropTableStmt = "drop TABLE %s;"%name_Table;`。
  • 好的。但是我在公共场合的桌子上有一个点,例如public.subname.name.how 删除那些?如果我只是删除 subname.name,我会在原始问题中得到错误
  • 那是个坏主意。您现在必须引用名称。最好的方法是drop TABLE quote_ident(%s)。然后花点时间在这里Identifiers 为您解决更多问题。
  • 你能回答吗?

标签: sql pandas postgresql schema psycopg2


【解决方案1】:

DROP TABLE public."subname.table" 做你想做的事。

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

【讨论】:

    【解决方案2】:

    public.subname.table 与该“。”中的Identifier 规则相冲突。不是有效字符。 解决方法是双引号标识符例如“public.subname.table”或使用函数quote_ident,如quote_ident(public.subname.table)。在你的情况下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 模块在查询字符串中正确安全地引用表名。

    【讨论】:

    • 不幸的是,当使用 drop TABLE quote_ident(%s) 时,我在 "(" LINE 1: drop TABLE quote_ident (public.subname.table); 处或附近出现语法错误
    • 查看我的 UPDATE 并找到有效的答案。
    猜你喜欢
    • 2019-01-09
    • 2019-01-17
    • 2020-04-18
    • 2022-01-15
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多