Nodejs oracledb详细解读

时间:2019-05-27
本文章向大家介绍Nodejs oracledb详细解读,主要包括Nodejs oracledb详细解读使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

node 连接 oracledb 代码模块。

具体配置连接数据库方式,请看oracledb原文地址:https://www.npmjs.com/package/oracledb

windows的环境搭建:https://www.cnblogs.com/caiyt/p/10129710.html,Linux也需要配置,Linux的配置具体百度一下,网上很多。

//导入oracledb模块 //基于版本@3.0.1  安装指令npm install oracledb
//node访问oracleDB需要搭建访问环境,否则无法正常访问
//创建Oracle对象
let oracledb  = null;

//引用配置参数模块
let configFile = require("./config");
//引用通用方法模块
let common = require("./commonHelper");

try{
    oracledb = require('oracledb');
}
catch (err) {
    console.log("oracledb声明错误原因:"+ err.message);
}


//默认config对象
let config=configFile.oracle_config;

let oracle={};

//配置存储过程是的输出输入,与参数类型
oracle.db=oracledb;

let connection = null;
async function initConnection()
{
    if(connection == null)
    {
        connection = await oracledb.getConnection(config);//配置默认连接池,配置过就无需再继续配置
    }
}

(async ()=>{
    //是否初始化数据库连接
    if(configFile.init_oracle)
    {
        await initConnection();
    }
})();

/**
 * 初始化连接参数
 * @param {string} user 用户名
 * @param {string} password 密码
 * @param {string} connectString 数据库连接字符串
 */
oracle.initConfig=function(user,password,connectString){
    config.user=user;
    config.password=password;
    config.connectString=connectString;
    connection = null;
}


//统计行号
let rowCount = 0;
/**
 * 执行sql文本(带params参数),由于要使用逐条读取所以只能通过回调返回数据
 * @param {string} sqlText 执行的sql语句
 * @param {JSON} params sql语句中的参数
 * @param {JSON} isToJson 每行都被提取为JavaScript对象
 * @param {function} func 回调函数 逐行读取数据返回
 */
oracle.queryWithParams= async function(sqlText,params,isToJson,func){
    try {
        let options = {resultSet: true, outFormat: oracledb.ARRAY};
        if (isToJson) {
            options = {resultSet: true, outFormat: oracledb.OBJECT};
        }
        //获取连接池内的连接
        oracledb.getConnection(config,
            function (err, connection) {
                //判断是否存在异常信息,是释放数据库连接与返回错误信息
                if (executeErr(err,connection,func)) {
                    return;
                }
                connection.execute(sqlText, params, options, async function (err, result) {
                    //判断是否存在异常信息,是释放数据库连接与返回错误信息
                    if (executeErr(err,connection,func)) {
                        return;
                    }
                    rowCount = 0;//初始化统计行号
                    fetchOneRowFromRS(connection, result.resultSet, func);
                })
            });
    }
    catch (err) {
        console.log(err)
        return {state:false,data:err.message};//返回错误信息
    }

};
//递归读取结果集的数据
function fetchOneRowFromRS(connection, resultSet,func) {
    resultSet.getRow( // get one row
        async function (err, row) {
            if (err) {
                console.error(err.message);
                await doClose(connection, resultSet); // 发生异常错误的时候关闭数据库连接
            } else if (!row) {               // 无数据的时候,关闭数据库连接
                await doClose(connection, resultSet);
            } else {
                rowCount++;
                common.consoleLog ("fetchOneRowFromRS(): row " + rowCount);
                common.consoleLog (row);
                func({state:true,data:row});//返回行数据
                fetchOneRowFromRS(connection, resultSet,func);
            }
        });
}

/**
 * 执行sql文本(带params参数)
 * @param {string} sqlText 执行的sql语句
 * @param {JSON} params sql语句中的参数
 * @param {JSON} isToJson 每行都被提取为JavaScript对象
 */
oracle.queryByParams=async function(sqlText,params,isToJson){
    try {
        let options = { outFormat: oracledb.ARRAY };
        if(isToJson)
        {
            options ={outFormat: oracledb.OBJECT };
        }
        await initConnection();//初始化连接
        let result = await connection.execute(sqlText,params,options);
        return {state:true,data:result};//返回查询的结果数据
    }
    catch (err) {
        await doReconnection(err.message,sqlText);
        return {state:false,data:err.message};//返回错误信息
    }
};


/**
 * 执行存储过程文本(带params参数)
 * @param {string} sqlText 执行的存储过程
 * @param {JSON} params sql语句中的参数
 * let params = {
       p1:  'Chris', // Bind type is determined from the data.  Default direction is BIND_IN
       p2:  'Jones',
       ret:  { dir: oracledb.BIND_OUT, type: oracledb.STRING, maxSize: 40 }
    };
 * 查询结果的常量outFormat选项oracledb.ARRAY    4001    将每行作为列值数组获取,oracledb.OBJECT    4002    将每行作为对象获取
 */
oracle.executePro=async function(sqlText,params){
    try {
        await initConnection();//初始化连接
        let result = await connection.execute(sqlText,params,{outFormat: oracledb.ARRAY });
        return {state:true,data:result};//返回存储过程执行结果数据
    }catch (err) {
        await doReconnection(err.message,sqlText);
        return {state:false,data:err.message};//返回错误信息
    }
};


/**
 * 执行一条数据插入,修改,删除,存储过程文本(带params参数)
 * @param {string} sqlText 执行的存储过程
 * "INSERT INTO test VALUES (:id, :nm)",
 * @param {JSON} params sql语句中的参数
 * 写法一:{ id : {val: 1 }, nm : {val: 'Chris'} }
 * 写法二:[1, 'Chris']
 */
oracle.execute=async function(sqlText,params){
    try {
        await initConnection();//初始化连接
        let result = await connection.execute(sqlText,params,{ autoCommit: true});
        return {state:true,data:result};//返回执行结果数据
    }catch (err) {
        await doReconnection(err.message,sqlText);
        return {state:false,data:err.message};//返回错误信息
    }
};


/**
 * 执行多条数据插入,修改,删除,存储过程,文本(带params参数)
 * @param {string} sqlText 执行的存储过程
 * let sql = "INSERT INTO em_tab VALUES (:a, :b)";
 * @param {JSON} params sql语句中的参数
 * 写法一:let params = [
 { a: 1, b: "Test 1 (One)" },
 { a: 2, b: "Test 2 (Two)" },
 { a: 3, b: "Test 3 (Three)" },
 { a: 4 },
 { a: 5, b: "Test 5 (Five)" }
 ];
 * 写法二:let params = [
 [1, "Test 1 (One)"],
 [2, "Test 2 (Two)"],
 [3, "Test 3 (Three)"],
 [4, null],
 [5, "Test 5 (Five)"]
 ];
 * @param {JSON} options sql语句中的参数
 * 写法一: let options = {
    autoCommit: true,//必须有这个自动提交参数
    bindDefs:
    [ { type: oracledb.NUMBER },
      { type: oracledb.STRING, maxSize: 15 }
    ] };
 写法二:
 let options = {
    autoCommit: true,//必须有这个自动提交参数
    bindDefs: {
      a: { type: oracledb.NUMBER },
      b: { type: oracledb.STRING, maxSize: 15 }
    } };
 */
oracle.executeMany=async function(sqlText,params, options){
    options = Object.assign({},options,{autoCommit: true});//默认配置执行语句自动提交
    try {
        await initConnection();//初始化连接
        let result = await connection.executeMany(sqlText,params,options);
        return {state:true,data:result};//返回执行结果数据
    }catch (err) {
        await doReconnection(err.message,sqlText);
        return {state:false,data:err.message};//返回错误信息
    }
};

//执行SQL语句错误回调函数释放数据库连接
function executeErr(err,connection,func) {
    if (err) {
        console.error(err.message);
        doRelease_async(connection);//释放数据库连接
        func({state:false,data:err.message});//返回错误信息
        return true;
    }
    return false;
}
//关闭当前数据库连接
oracle.doClose =async function () {
    if(connection)
    {
        try {
            await connection.close();
        }
        catch (err) {
            console.error(err.message);
        }
    }
}

//关闭数据库连接
function doRelease_async(connection) {
    if(connection)
    {
        connection.close(
            function(err) {
                if (err) { console.error(err.message); }
            });
    }
}

//重新连接数据库
async function doReconnection(message,sqlText) {
    let time=new Date().Format("HH:mm:ss");
    common.writeLog("oracle_connection",time  + common.partition +sqlText+ common.partition + message);
    console.log(message);
    //释放连接,重新连接oracle
    if(message.search("not connected to ORACLE")>=0 || message.search("invalid connection")>=0 || message.search("未连接到 ORACLE") >=0 )
    {
        connection = null;//重新初始化oracle连接
    }
}

//关闭结果集在关闭数据库连接
async function doClose(connection, resultSet) {
    try {
        if(resultSet)
        {
            await resultSet.close();//释放读取流
        }
        if(connection)
        {
            await connection.close();//释放连接,将连接放回池中
        }
    }
    catch (err) {
        console.error(err.message);
    }
}

module.exports=oracle;

原文地址:https://www.cnblogs.com/caiyt/p/10929146.html