如何关闭 psycopg2 和 postgresql 之间的旧连接?
how to close a old connection between psycopg2 and postgresql?
我一直在使用 psycopg2 在多模块模型(我的博士论文)中控制本地 postgresql 服务器。
一段时间后我在模型中遇到一个错误并且它保持了一个幻影连接,当我 运行 模型与 postgresql 服务器的新连接时,它会调用其他模块时造成麻烦模型。
我的电脑同时显示多个postgresql连接,一共十个。较旧的连接在属性中具有 35 天前的最后修改。
我卸载了python、postgresql并删除了数据库,然后我重新安装了所有东西,问题仍然存在。
如有嘉宾或帮助,不胜感激
如果您是超级用户,您可以按照答案here.
中的描述关闭现有连接
根据您的应用程序,您还可以查看修改应用程序连接到数据库的方式。使用类似以下内容创建名为 mydb.py 的文件:
import psycopg2
import psycopg2.pool
from contextlib import contextmanager
dbpool = psycopg2.pool.ThreadedConnectionPool(host=<<YourHost>>,
port=<<YourPort>>,
dbname=<<YourDB>>,
user=<<YourUser>>,
password=<<yourpassword>>,
)
@contextmanager
def db_cursor():
conn = dbpool.getconn()
try:
with conn.cursor() as cur:
yield cur
conn.commit()
except:
conn.rollback()
raise
finally:
dbpool.putconn(conn)
那么您的代码可以使用:
import mydb
def myfunction():
with mydb.db_cursor() as cur:
cur.execute("""Select * from blahblahblah...""")
我一直在使用 psycopg2 在多模块模型(我的博士论文)中控制本地 postgresql 服务器。
一段时间后我在模型中遇到一个错误并且它保持了一个幻影连接,当我 运行 模型与 postgresql 服务器的新连接时,它会调用其他模块时造成麻烦模型。
我的电脑同时显示多个postgresql连接,一共十个。较旧的连接在属性中具有 35 天前的最后修改。
我卸载了python、postgresql并删除了数据库,然后我重新安装了所有东西,问题仍然存在。
如有嘉宾或帮助,不胜感激
如果您是超级用户,您可以按照答案here.
中的描述关闭现有连接根据您的应用程序,您还可以查看修改应用程序连接到数据库的方式。使用类似以下内容创建名为 mydb.py 的文件:
import psycopg2
import psycopg2.pool
from contextlib import contextmanager
dbpool = psycopg2.pool.ThreadedConnectionPool(host=<<YourHost>>,
port=<<YourPort>>,
dbname=<<YourDB>>,
user=<<YourUser>>,
password=<<yourpassword>>,
)
@contextmanager
def db_cursor():
conn = dbpool.getconn()
try:
with conn.cursor() as cur:
yield cur
conn.commit()
except:
conn.rollback()
raise
finally:
dbpool.putconn(conn)
那么您的代码可以使用:
import mydb
def myfunction():
with mydb.db_cursor() as cur:
cur.execute("""Select * from blahblahblah...""")