Node.js实现mysql连接池使用事务自动回收连接的方法示例
本文实例讲述了Node.js实现mysql连接池使用事务自动回收连接的方法。分享给大家供大家参考,具体如下:
var mysql = require('mysql'), Connection = require('mysql/lib/Connection.js'); var pool = mysql.createPool({ host: '127.0.0.1', database: 'myDB', port: 3306, user: 'root', password: 'root', debug: false, connectionLimit: 3 }); var execPool = function() { pool.getConnection(function(err, conn) { transAutoRelease(conn); conn.beginTransaction(function(err) { if (err) throw err; conn.query("INSERT INTO test(id,name,date,test) values(1,'123',now(),1)", function(err, ret) { if (err) { console.error(err); conn.rollback(function() {}); } else { console.log(ret); conn.query('UPDATE test set id=12321312 where id=1', function(err, ret) { if (err) { console.error(err); conn.rollback(function() { }); } else { conn.commit(function() { console.log('success' + JSON.stringify(ret)); }); } }); } }); }); }); } function after(fn, cb) { return function() { fn.apply(this, arguments); cb(); } } function transAutoRelease(conn) { if (conn.commit == Connection.prototype.commit) conn.commit = after(conn.commit, release); if (conn.rollback == Connection.prototype.rollback) conn.rollback = after(conn.rollback, release); function release() { if (conn) { conn.release(); } } } var intervalStartProcess = function() { setInterval(function() { execPool(); }, 1000); } for (var i = 5 - 1; i >= 0; i--) { intervalStartProcess(); }
希望本文所述对大家nodejs程序设计有所帮助。
相关推荐
huacuilaifa 2020-10-29
CoderToy 2020-11-16
emmm00 2020-11-17
王艺强 2020-11-17
ribavnu 2020-11-16
bianruifeng 2020-11-16
wangshuangbao 2020-11-13
苏康申 2020-11-13
vivenwan 2020-11-13
moyekongling 2020-11-13
云中舞步 2020-11-12
要啥自行车一把梭 2020-11-12
aydh 2020-11-12
kuwoyinlehe 2020-11-12
minerk 2020-11-12
vitasfly 2020-11-12
jazywoo在路上 2020-11-11
敏敏张 2020-11-11