Node.js MySQL事务 [英] Node.js mysql transaction
问题描述
任何人都可以提供一个示例,说明如何在Node.js中实现MySQL事务.我正在尝试使用node-mysql驱动程序和node-mysql-queue来解决问题.
Can anyone provide an example of how I could achieve MySQL transactions in Node.js. I am trying to get my head around using the node-mysql driver and node-mysql-queue.
据我所知,使用node-mysql-queue大大降低了Node.js的异步性,因为新查询必须等待现有查询完成.为了解决这个问题,有没有人试图将node-mysql-queue与node-mysql的连接池功能结合在一起.即为每个新的http请求启动一个新的mysql连接,并在各个连接上启动事务队列?
As far are I can tell, using node-mysql-queue greatly reduces the asynchronous nature of Node.js as new queries have to wait until existing ones have completed. To get around this, has anyone attempted to combine node-mysql-queue with node-mysql's connection-pooling capabilities. i.e starting a new mysql connection for each new http request, and starting transaction queues on individual connections?
推荐答案
一个月前,以下事务示例已添加到文档中:
The following transaction example was added to the documentation a month ago:
https://github.com/felixge/node-mysql#transactions
connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
var log = 'Post ' + result.insertId + ' added';
connection.query('INSERT INTO log SET data=?', log, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
console.log('success!');
});
});
});
});
这篇关于Node.js MySQL事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!