node-odbc接口简介

Node.js可以通过node-shentongdb访问神通数据库,也可以通过node-odbc方式访问数据库,node-odbc是一个可以访问任意支持odbc驱动的数据库插件,它依赖数据库的odbc驱动,因此在使用它操作数据库时,需要配置好odbc的环境。

Node-odbc安装

安装 nodejs

yum install nodejs

unixodbc 安装

odbc 版本:2.3.1

安装方式:源码安装

安装过程:

./configer

make

make install

Linux下请配置Unixodbc下的数据源,比如odsn的。神通数据库的数据源配置详细参与ODBC程序员开发手册中的内容。

Node-odbc 安装

node-odbc下载地址:https://github.com/wankdanker/node-odbc/

node-gyp是跨平台的node.js模板编译的工具。

安装时方式:

npm install –g node-gyp

编译模块,比如编译odbc,到odbc node模块中执行:

node-gyp configure

node-gyp build

简单使用

使用node-odbc时,需要引入odbc模块:

db = require("odbc")

简单查询

数据库:

Create table test( a int ,b varchar(100));
Insert into test values(1,'a');
Insert into test values(1,'a123456789');
Insert into test values(1,'神通数据库');

代码,index.js:

var db = require("odbc")(),cn = "DSN=odsn;Uid=sysdba;Pwd=szoscar55;";
db.open(cn,function(err){
        if(err) return console.log(err);
        db.query('select * from test',function(err,data)
        {
        if(err)  console.log(err);
        console.log(data);
                db.close(function(){
                console.log('done');
                });
        });
});

带参数查询

数据库:

Create table test( a int ,b varchar(100));

代码,index-insert.js:

var db = require("odbc")(),cn = "DSN=odsn;Uid=sysdba;Pwd=szoscar55;";
db.openSync(cn);
var stmt = db.prepareSync("insert into test VALUES (?, ?)");
stmt.execute([42,'神通数据库是大型国产安全数据库!'], function (err, result) {
  result.closeSync();
  db.closeSync();
});

注意事项

  • node-odbc模块不同版本可能存在一下问题,使用时需要注意;