Asnycpg PostgreSQL连接问题



我使用Python与asnycpg与我的PostgreSQL数据库交互。一段时间后,如果我不与它交互,然后尝试这样做,我得到一个连接已关闭错误。这是服务器端配置还是客户端配置问题?如何解决?

由于安全原因,数据库自动关闭连接。

所以我建议你在使用asyncpg运行查询之前打开到db的连接,然后在之后关闭连接。

此外,您可以通过适当地引发异常来管理连接关闭时可能出现的错误。

看一下这个例子:

Import asyncpg
print("I'm going to run a query with asyncpg")
# if the connection to db is not opened, then open it
if not connection:
# try to open the connection to db
try:
connection = await asyncpg.connect(
host=YOUR_DATABASE_HOST,
user=YOUR_DATABASE_USER,
password=YOUR_DATABASE_PASS,
database=YOUR_DATABASE_DB_NAME
)
except (Exception, asyncpg.ConnectionFailureError) as error:
Print("Error while connecting to db: {}".format(error))
else:
#connection already up and running
pass
QUERY_STRING = """
INSERT INTO my_table(field_1, field_2)
VALUES ($1, $2);
"""
try:
await connection.execute(QUERY_STRING, value_to_assign_to_field_1, value_to_assign_to_field_2)
return None
# except (Exception, asyncpg.UniqueViolationError) as integrError:
# print("You are violating unique constraint.")
except (Exception, asyncpg.ConnectionFailureError) as error:
print("Connection to db has failed. Cannot add data.")
return "{}".format(error)
finally:
if (connection):
await Utils.close_connection(connection)
print("data has been added. closing the connection.")

相关内容

  • 没有找到相关文章

最新更新