我正在编写代码,以便在Anaconda的Spyder环境中用Python创建GUI。在此代码中,我使用PostgreSQL数据库,因此使用了psycopg2数据库适配器,以便可以直接从GUI进行交互。
代码太长,无法在此处发布,因为它超过3000行,但总而言之,除了尝试删除表时,与数据库交互没有问题。
这样做时,GUI框架将无响应,drop table
查询不会删除预期的表,并且不会引发任何错误或其他任何此类情况。
在我的代码中,所有导致删除表的操作都通过函数(DeleteTable
)处理。当我调用此函数时,没有问题,因为我之前插入了几条打印语句,这些语句确认一切正常。当我使用cur.execute(sql)
行代码执行语句时,就会发生问题。
有人能弄清楚为什么我的桌子不会掉落吗?
def DeleteTable(table_name):
conn=psycopg2.connect("host='localhost' dbname='trial2' user='postgres' password='postgres'")
cur=conn.cursor()
sql="""DROP TABLE """+table_name+""";"""
cur.execute(sql)
conn.commit()
答案 0 :(得分:2)
那一定是因为并发事务持有锁定target="_blank"
语句的锁。
检查DROP TABLE
视图并注意与pg_stat_activity
等于state
或idle in transaction
且active
超过几秒钟的会话
这实质上是一个应用程序错误:您必须确保立即关闭所有事务,否则可能会发生不良情况。
答案 1 :(得分:0)
在气流的postgres挂钩中使用psycopg2时遇到相同的问题,我用with statement
解决了。也许可以解决此问题,因为该连接在with statement
中是本地的。
def drop_table():
with PostgresHook(postgres_conn_id="your_connection").get_conn() as conn:
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS your_table")
task_drop_table = PythonOperator(
task_id="drop_table",
python_callable=drop_table
)
对于上面的原始代码,这样的解决方案是可能的(我没有对此进行测试):
def DeleteTable(table_name):
with psycopg2.connect("host='localhost' dbname='trial2' user='postgres' password='postgres'") as conn:
cur=conn.cursor()
sql="""DROP TABLE """+table_name+""";"""
cur.execute(sql)
conn.commit()
如果有人尝试,请发表评论。