我在nodejs中使用ibm_db。
根据文档idb_db module,我知道db2具有事务回滚和提交。
我的问题是如何从ibm_db模块访问数据库类/接口。
我仍然想使用db2缓冲池功能来管理我的数据库缓冲池,但是我仍然希望对我的控制器类进行事务回滚和提交,因为我对多个表有多个sql语句。
控制器类:
//begin tranaction
try {
//SOME SQL 1
//SOME SQL 2
//COMMIT
}
catch (err) {
//ROLLBACK
}
//end transaction
DAO类:
var connectionString = require('../common/ibmdb2Pool').connectionString;
var connString = connectionString();
var initPool = require('../common/ibmdb2Pool').initPool;
var pool = initPool();
const query = require('../db/query');
function updatePerson(params, fin, callback) {
pool.open(connString, function (err, conn) {
conn.prepare(query.SQL_UPDATE_PERSON, function (error, stmt) {
if (err) {
console.error(err);
return conn.closeSync();
}
stmt.executeNonQuery(params, function (err, result) {
if( err ) {
console.error(err);
}
else {
console.debug("Affected rows = " + result);
}
//Close the connection
conn.close();
//return result as callback.
return callback([fin, result]);
});
});
});
}
ibmdb2Pool类:
//imports
require('dotenv').config();
var Pool = require("ibm_db").Pool;
// access the environment variables for this environment
...
const CONNSTRING = DATABASE + HOSTNAME + UID + PWD + DB_PORT + PROTOCOL;
//variables
const MIN_POOL_SIZE = 20;
const MAX_POOL_SIZE = 100;
//return connection string from environment file.
exports.connectionString = function () {
return CONNSTRING;
};
//init the db pool with a min and max size
exports.initPool = function () {
var pool = new Pool();
var ret = pool.init(MIN_POOL_SIZE, CONNSTRING);
if(ret !== true) {
console.error("Cannot init pool. " + ret);
}
pool.setMaxPoolSize(MAX_POOL_SIZE);
return pool;
};