Node.js运用mssql模块链接SQL Server数据库

现在数据库的类型越来越多,比如node.js经常使用的MySQL,mongdb等,由于之前经常用SQL Server数据库,所以打算做一个node链接SQL Server的demo,网上找了很多方法,查到了好几个方法比如node-sqlserver模块和msnodesql 模块,但这两者对环境的要求比较高,感觉很麻烦,继续百度到了mssql模块,还是挺简单的。

(1)安装mssql模块

npm install mssql 

(2)数据库连接  创建db.js

var mssql = require('mssql');
var db = {};
var config = {
    user: 'sa',
    password: '密码',
    server: '服务器',
    port:1433,
    driver: 'msnodesql',
    database: '数据库',
    connectionString: "Driver={SQL Server Native Client 11.0};Server=#{server}\\sql;Database=#{database};Uid=#{user};Pwd=#{password};",
/*    options: {
        encrypt: true // Use this if you're on Windows Azure
    },*/
    pool: {
        min: 0,
        max: 10,
        idleTimeoutMillis: 3000
    }
};
(3)数据库封装

db.sql = function (sql, callBack) {
    var connection = new mssql.ConnectionPool(config, function (err) {
        if (err) {
            console.log(err);
            return;
        }
        var ps = new mssql.PreparedStatement(connection);
        ps.prepare(sql, function (err) {
            if (err){
                console.log(err);
                return;
            }
            ps.execute('', function (err, result) {
                if (err){
                    console.log(err);
                    return;
                }

                ps.unprepare(function (err) {
                    if (err){
                        console.log(err);
                        callback(err,null);
                        return;
                    }
                    callBack(err, result);
                });
            });
        });
    });
};

module.exports = db;
(4)引用 创建dbtest.js

var express = require('express');
var app = express();
var db = require('./db');

db.sql('select * from OuiesNews',function(err,result){

    if (err) {
        console.log(err);
        return;
    }
    app.get('/',function (req,res){
        res.send(result.recordsets[0][1].TITLE);
    })
});
app.listen(3000);





猜你喜欢

转载自blog.csdn.net/zhengjie0722/article/details/78397018