Javascript 从node.js中的PostgreSQL查询返回查询结果状态
我使用Javascript 从node.js中的PostgreSQL查询返回查询结果状态,javascript,node.js,postgresql,Javascript,Node.js,Postgresql,我使用pg模块将node.js服务器连接到PostgreSQL数据库。有一次,我将为一个httppost将数据插入两个不同的数据库表中。如果第一个查询失败,则不应执行第二个查询,但我在实现这一点时遇到了一些困难 我的通用查询函数如下所示: // General insertion function. If endResponse is true, the response will be ended, // if it is false it will just write to the res
pg
模块将node.js
服务器连接到PostgreSQL数据库。有一次,我将为一个httppost
将数据插入两个不同的数据库表中。如果第一个查询失败,则不应执行第二个查询,但我在实现这一点时遇到了一些困难
我的通用查询函数如下所示:
// 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
返回true
和false
,但由于这些是内部函数,因此无法从外部函数正确返回结果。另外,如果它是异步运行的,那么有些问题也会变得更加困难。在调用performInsertQuery
时,我也无法使用try/catch
。我想我可以再做一次查询,看看是否插入了数据,但这似乎是不必要的,也不是很可靠
从
performInsertQuery
返回成功或失败状态的最佳方法是什么?我知道这并不能完全按照您的意图处理您的问题(完全在node.js中处理),但这听起来像是Postgres事务的一个极好的用例……除非所有插入/更新都成功,否则不要提交结果。SQL事务是为您这样的场景构建的
下面是节点模块的文档和示例代码。
酷,我不知道交易。我认为这是解决我的问题的一种更有效的方法。我只在total查询的开头添加了一个
BEGIN
,在末尾添加了一个COMMIT
,并保留了问题中的插入功能。如果作者正确地表述了他的问题,那么这个答案是不正确的。使用事务可能会导致第一个查询成功,第二个查询失败,这将回滚第一个查询的结果,这不是作者要求的。好吧,这是我想问的,我只是不知道怎么做,因为我是一个JavaScript noob,不知道事务或它们是如何工作的。无论如何,您是对的,使用pgpromise
或其他promise
库是一种比我在这个问题上的方法更好的选择。我也不知道承诺和相关的事情,但现在我知道了。谢谢。你的代码有太多的问题要在这里列出,首先是PG库实例化的错误方法,错误的连接用法,错误的调用client.end()
,等等。如果你想避免这种不洁的混乱,试着,这将隐藏与连接和查询排序相关的所有复杂性。