node oracledb

官方参考地址 

https://oracle.github.io/node-oracledb/doc/api.html

https://oracle.github.io/node-oracledb/INSTALL.html

1、安装oracledb

npm install oracledb
2、配置oracle client 客户端

E:\instantclient-basic-windows.x64-18.3.0.0.0dbru\instantclient_18_3
3、数据库配置文件

oracledbConfig:{
    user: username,
    password: password,
    connectString: "ip:1521/ORCL.TEST"
  }


4、数据库连接与数据库查询

/*
 * @Author: 苹果园dog
 * @Date: 2021-05-06 17:54:15
 * @LastEditTime: 2021-05-11 17:00:33
 * @LastEditors: Please set LastEditors
 * @Description: oracle数据库操作库
 * @FilePath: \tongliao\tongliao.server.node\routers\oracledbUtil.js
 */
var globalConfig = require("../config/config.js")
const Oracledb = require('oracledb');
function connect(config) {
  return new Promise(function (resolve, reject) {
    try {
      Oracledb.getConnection(config, function (err, conn) {
        if (err) {
          console.log(err.message);
          console.log("oracle数据库连接失败");
          resolve({
            status: -1,
            msg: '数据库连接失败',
            detail: err.message
          })
          return
        }
        console.log("oracle数据库连接成功");
        resolve(conn);
      });
    } catch (ex) {
      console.log("oracle数据库连接出错");
      resolve({
        status: -1,
        msg: '数据库连接出错',
        detail: ex || '数据库连接时出现未知原因错误'
      })
    }
  });
}


(async () => {
  let conn = await connect(globalConfig.oracledbConfig);
  doRelease(conn);
})()

function doRelease(conn) {
  if(!conn||!conn.close){
    return;
  }
  conn.close(
    function (err) {
      if (err) {
        console.log(err.message)
        return
      }
      console.log('oracle数据库连接已断开!')
    });
}

async function query(sql) {
  let conn = await connect(globalConfig.oracledbConfig)
  if(!conn){
    return null;
  }
  let data = await execute(conn, sql)
  doRelease(conn)

  return data
}

module.exports = {
  query: query
}

 


5、实例

 

/*
 * @Author: 苹果园dog
 * @Date: 2021-05-11 10:11:38
 * @LastEditTime: 2021-05-11 15:35:11
 * @LastEditors: Please set LastEditors
 * @Description: 测试外部数据oracle
 * @FilePath: \test.js
 */
var express = require("express");
var app = express.Router();
var oracleUtil = require("../oracledbUtil.js");
app.get("/", (req, res) => {
    var sql = ` select * from  tabletest  order by id `;
    oracleUtil.query(sql).then(function(data){
        res.send({
            succeed: 1,
            data: data,
            message: '查询成功'
        });
    }).catch(function(reason){
        res.send({
            code: 500,
            message: "查询失败!",
            err: reason
        });
    });
});

module.exports = app

 

posted on 2021-05-11 17:03  苹果园dog  阅读(124)  评论(0编辑  收藏  举报

导航