gpt4 book ai didi

javascript - 从node.js中的PostgreSQL查询返回查询结果状态

转载 作者:行者123 更新时间:2023-12-03 10:10:39 25 4
gpt4 key购买 nike

我有一个使用 pg 模块连接到 PostgreSQL 数据库的 node.js 服务器。在某一时刻,我会将数据插入到单个 HTTP POST 的两个不同的数据库表中。如果第一个查询失败,则不应执行第二个查询,但我在实现这一点时遇到了一些麻烦。

我的广义查询函数如下所示:

// General insertion function. If endResponse is true, the response will be ended,
// if it is false it will just write to the response and not end it (unless errors occurs).
function performInsertQuery(request, response, query, endResponse) {
var pg = require('pg');

var client = new pg.Client(request.app.get('postgreConnection'));
client.connect(function(error) {
if (error)
{
message = 'Could not connect to PostgreSQL database: ' + error;
response.end(message);
console.error(message);
client.end();
}
else
{
client.query(query, function (error, result)
{
if (error)
{
var message = 'Error running query ' + query + ': ' + error;
response.writeHead(500, {'content-type':'application/json'});
response.end(message);
console.error(message);
client.end();
}
else
{
var message = 'Query performed: ' + query;
if (endResponse)
{
response.end(message);
}
else
{
response.write(message + '\n');
}
console.log(message);
client.end();
}

});
}
});
}

后来,我得到了类似以下内容:

// query = some query
performInsertQuery(request, response, query, false);

// Stop running here if there was any errors running the query.

// Currently, this gets executed even though the first query fails.
// anotherQuery = another query
performInsertQuery(request, response, anotherQuery, true);

我尝试从函数 performInsertQuery 返回 truefalse,但由于这些是内部函数,因此无法从函数中正确返回结果外部函数。另外,有些如果是异步运行的,这也会让事情变得有点困难。我也无法使其与 try/catch 围绕对 performInsertQuery 的调用一起工作。我想我可以再做一次查询来查看是否插入了数据,但这似乎没有必要,而且不是很健壮。

performInsertQuery 返回成功或失败状态的最佳方式是什么?

最佳答案

我知道这并不能完全按照你的预期处理你的问题(完全在node.js中处理这个问题),但这听起来像是Postgres事务的一个很好的用例......不要提交结果,除非所有插入/更新成功。 SQL 事务是为像您这样的场景而构建的。

以下是您的 Node 模块的文档和示例代码。 https://github.com/brianc/node-postgres/wiki/Transactions

http://www.postgresql.org/docs/9.2/static/tutorial-transactions.html

关于javascript - 从node.js中的PostgreSQL查询返回查询结果状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com