与数据库的连接将正确关闭? psycopg2
我已经使用了大约10天的代码,而且效果很好。今天,它带着一条错误消息崩溃:
file“/home/ubuntu/jag-bot/utils/db.py”,第22行,在check_user中 与self.connection: psycopg2.interfaceerror:连接已经关闭
代码:
@dataclass
class Database:
def __init__(self):
self.connection = psycopg2.connect(config.DB_URI, sslmode='require')
self.cursor = self.connection.cursor()
self.current_date = utc.localize(datetime.now())
def check_user(self, user_id):
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
result = self.cursor.fetchone()
if result:
return True
return False
更新: 用错误处理修复。 我是否需要此行'self.cursor = self.connection.cursor()'在块中?
def check_user(self, user_id):
try:
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
except psycopg2.InterfaceError as exc:
self.connection = psycopg2.connect(DB_URI)
# self.cursor = self.connection.cursor() What about this string?
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
finally:
result = self.cursor.fetchone()
if result:
return True
return False
I have used this code for ~10 days and it worked just fine. Today it crashed with an error message:
File "/home/ubuntu/jag-bot/utils/db.py", line 22, in check_user
with self.connection:
psycopg2.InterfaceError: connection already closed
Code:
@dataclass
class Database:
def __init__(self):
self.connection = psycopg2.connect(config.DB_URI, sslmode='require')
self.cursor = self.connection.cursor()
self.current_date = utc.localize(datetime.now())
def check_user(self, user_id):
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
result = self.cursor.fetchone()
if result:
return True
return False
UPDATE:
Fixed with error handling.
Do I need this line 'self.cursor = self.connection.cursor()' in except block?
def check_user(self, user_id):
try:
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
except psycopg2.InterfaceError as exc:
self.connection = psycopg2.connect(DB_URI)
# self.cursor = self.connection.cursor() What about this string?
with self.connection:
self.cursor.execute(f"SELECT user_id FROM mango WHERE user_id = {user_id}")
finally:
result = self.cursor.fetchone()
if result:
return True
return False
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是Jagster维护者解决的已知问题。请将数据库模块更新为PYPI版本0.1.5或更高版本。您可以在此处找到有关如何执行此操作的说明: https://github.com /jagster-bot/jagster-bot/essess/1218
This is a known issue that has been fixed by the maintainers of Jagster. Please update your database module to version 0.1.5 or higher from PyPI. You can find instructions on how to do so here: https://github.com/Jagster-Bot/Jagster-Bot/issues/1218