连接到我的 postgres 数据库时出错会发生什么情况? (节点)
我使用 node-postgres
连接到我的 postgres 数据库。如果我的 SQL 查询失败会发生什么?我是否必须手动关闭连接(client.end()
)还是 Postgres 会自动关闭它? 通常,我手动关闭连接,但我想知道这是否仅在成功查询数据库时才需要。
谢谢 卢卡斯
I use node-postgres
to connect to my postgres database. What happens if my SQL-Query fails? Do I have to close the connection manually (client.end()
) or does Postgres closes this automatically?
Normally, I manually close the connection but I wonder if this is only necessary when successfuly querying my database.
Thanks
Lukas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这完全取决于您的结构以及数据库调用发生的频率。
如果您的服务器接收多个请求并执行数据库操作,那么最好使用池,这样您就可以在服务器初始化时连接数据库,并在服务器终止时销毁连接。你不需要建立额外的连接,node-postgres池会安排它。在池结构中,您不需要取消查询失败的连接事件。泳池会处理这个问题。
如果您使用像 lambda 这样的单一函数,那么手动管理连接是明智的。因此,每次调用函数时,您都会创建连接,而当函数完成其工作时,您会销毁连接。通过这种方式,您需要确保捕获全局级别的错误并手动销毁连接。
.finally()
语句会很有帮助。It all depends how your structure is and how often DB calls will happen.
If you have a server that gets multiple requests and do DB actions it is good use
pool
so you connect the DB on server init and destroy your connection on when server dies. You don't need to make extra connection, node-postgres pool will arrange it. Within the pool structure you don't need to cancel the connection event your query fails. Pool will manage that.If you a single functions like lambdas it is wise to manage connection manually. So everytime function gets called you create connection and when the function does its job you destroy connection. In this way you need to make sure to catch the errors on global level and destroy connection manually. a
.finally()
statement would be helpful.