1.基础环境
nodejs: 64bit,v12.16
oracle: 64bit,11gR2,分布式安装
oracle客户端:instantclient-basic-windows.x64-11.2.0.4.0.zip、instantclient-sdk-windows.x64-11.2.0.4.0.zip。在navicat中,还需要 instantclient-sqlplus-windows.x64-11.2.0.4.0.zip。可以从官网下载
2.环境配置
1)将instantclient-basic-windows.x64-11.2.0.4.0.zip、instantclient-sdk-windows.x64-11.2.0.4.0.zip解压到统一目录中,例如 E:\Software\win64_11gR2_client\instantclient_11_2
2)配置系统变量,在path中增加E:\Software\win64_11gR2_client\instantclient_11_2值,放在最前面,以防止覆盖,并添加以下变量
3)安装 npm install oracledb,并在代码中调用
const oracledb = require('oracledb');
*{
"connectString": "192.168.1.241:1521/ORCL",
"user":"sys001",
"password":"orcl"
*}
oracledb.getConnection(_conn,function (err,connection) {
if(err) {
log4.errorLog("初始化oracle数据库"+_conn.connectString+"连接失败,错误信息"+err.message);
connection&&connection.close();
return;
}else{
client = connection;
log4.infoLog("初始化oracle数据库【"+_conn.connectString +"】连接成功");
}
});
4)如果执行报环境错误,可以手动设置oracle环境,
try {
oracledb.initOracleClient({libDir: 'E:\\Software\\win64_11gR2_client\\instantclient_11_2'});
} catch (err) {
console.error('Whoops!');
console.error(err);
}
5)oracle参数化执行,并将执行结果数组转json
var _params = [1,"张三"];
var _index = 1;
client.execute(sqlstr,_params,function(err, result) {
var _rt="fail";
if (err){
log4.errorLog("执行"+sqlstr+",出现参数错误,错误信息:"+err.message);
}else {
if (result.rows != undefined){
//数组转json结构
var _data = [];
for (var i = 0; i < result.rows.length; i++) {
var _temp = {};
for (var j = 0; j < result.metaData.length; j++) {
_temp[result.metaData[j]['name']] = result.rows[i][j];
}
_data.push(_temp);
}
_rt = _data;
}else
_rt ="success";
}
if(cb&&typeof cb == "function") {
cb(_rt);
}
});
6)设置自动提交,update、delete才会实时生效
oracledb.autoCommit = true;