利用tedious连接,github地址:https://github.com/tediousjs/tedious
废话不多时直接上代码。
connection.js
var Connection = require('tedious').Connection; var Request = require('tedious').Request; exports.mssql = function(config){ this.connection = new Connection(config); this.query = function(str,callback){ //执行查询 var connection = this.connection; var rows={}; connection.on('connect', function(err){ //连接数据库,执行匿名函数 if(err){ callback({'err':err['message']+'请检查账号、密码是否正确,且数据库存在'}); }else{ var request = new Request(str,function(err, rowCount){ if(err)err = {'err':err['message']}; callback(err,rows); connection.close(); }); var n=0; request.on('row', function(columns) { //查询成功数据返回 rows[n]={}; columns.forEach(function(column) { rows[n][column.metadata.colName] = column.value; //获取数据 }); n++; }); connection.execSql(request); //执行sql语句 } }); } }
test_connection.js
var mssql = require('./tedious/connection.js'); // var conn = new mssql.mssql({'userName':'sa','password':'123456','server':'192.168.0.135','options':{'port':1433,'database':'hybtest'}}); // conn.query('select * from db_user', function(err,data){ var conn = new mssql.mssql({ 'userName':'sa', 'password':'123456', 'server':'192.168.0.134', 'options':{ 'port':1433, 'database':'hybtest', tdsVersion:"7_1"//sql server 2000 的需要加上这个,其他版本请注释此参数 } }); conn.query('select * from test_user', function(err,data){ if(!err){ console.log(data) //成功返回数据 } else { console.log(err) //出错返回 } } );
运行 node test_connection.js 可查看结果。