【问题标题】:Cannot create temporary tables in postgres using psycopg2无法使用 psycopg2 在 postgres 中创建临时表
【发布时间】:2020-09-01 01:29:24
【问题描述】:

我正在尝试在 postgres 中创建一个临时表。我正在使用 psycopg2。但是,在执行我的 python 脚本时,我没有看到正在创建的表。如果我尝试创建一个普通表,它会毫无问题地执行。有什么我遗漏的概念吗?我的目的是创建一个临时表,然后将数据导入临时表,进行一些处理,然后将临时表数据推送到永久表中。

下面是我的代码

import psycopg2

con = None
con = psycopg2.connect("dbname='abc' user='abc' host='localhost' password='abc'")
cur = con.cursor()
cur.execute("create TEMP TABLE mytable(id int);")
con.commit()
con.close()

如果我使用终端执行相同的create TEMP TABLE mytable(id int);,它会创建临时表。

感谢@Thom Brown 的回复。

我确实想到了你的观点。为了绕过 con.close() 的问题,我做了以下,但没有成功。

con = None
con = psycopg2.connect("dbname='abc' user='abc' host='localhost' password='abc'")
cur = con.cursor()
cur.execute("create temp table mynewtable(id int) on commit delete rows;")
cur.execute("BEGIN TRANSACTION;")
cur.execute("insert into mynewtable values(10);")
//created a new normal table from console
cur.execute("select * into dbo.test from mynewtable;")
#cur.execute("select * into test from mynewtable;")
cur.execute("commit")
con.commit()
con.close()

理论上,我应该能够使用执行命令创建临时表,向其中插入一些数据,将所有数据从临时表传输到永久表,关闭连接。临时表数据将丢失,但永久表应该有传输的数据。这没有发生。请指导。

【问题讨论】:

    标签: mysql postgresql psycopg2 psql


    【解决方案1】:

    临时表在会话结束时被销毁。当您使用con.close() 关闭连接时,临时表将被删除。

    如果您希望使用临时表,则需要在关闭连接之前进行。

    【讨论】:

    • 在您的示例中,您是否有一个名为“test”的表,但其中没有数据?
    • 是的,我已经直接使用终端创建了一个单独的普通表。
    • 您正在使用 SELECT INTO,这意味着您不需要手动创建表。如果您在其他地方创建它,该语句将失败。
    • 太棒了!!使用select into 创建永久表就可以了。但这意味着,我无法从临时表创建自己的永久表,例如使用额外的列。我必须发出另一个查询来添加/更改永久表
    • 如果您想将数据插入到您提前创建的表中,您只需要使用INSERT INTO test (col1,col2,col3) SELECT col1, col2, col3 FROM mynewtable; 之类的东西,这样您就可以在需要时在永久表中添加其他列.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    相关资源
    最近更新 更多