26

The question duplicates some older questions, but the things may have changed since then.

Is there some official support for connecting to SQL Server from Node.js (e.g. official library from MS)? Or at least some well-maintained third-party library appropriate for a production-grade application?

We usually use ASP.NET MVC/SQL Server combination, but currently I have a task for which express/Node.js seems to be more appropriate (and I'd like to play with something new), so the question is whether we can rely on a Node.js and SQL Server interaction.

UPD: It seems that Microsoft has, at last, released the official driver: https://github.com/WindowsAzure/node-sqlserver

penartur
  • 9,792
  • 5
  • 39
  • 50
  • I've been looking for a solution for this for a couple of weeks now... thanks for adding the question. Right now I'm also using a thin MVC app to handle the SQL connection but I don't like it. It's annoying that all the answers I can find point to the same non-working modules. – Marcel Popescu Apr 28 '12 at 07:57
  • 1
    @MarcelPopescu https://github.com/pekim/tedious seem to work for me, with the following limitations: it does not support transactions (even those not explicitly issued by you but occurring in stored procedures), and it does not support procedures returning multiple result sets. The procedures returning multiple result sets should be rewritten anyway IMHO; but living without transactions is limiting Node.js+MSSQL usage to a simple nearly transparent frontends (thankfully, this is what I'm writing). – penartur May 01 '12 at 11:53
  • 2
    @MarcelPopescu Actually, MS just released an official MSSQL driver: https://github.com/WindowsAzure/node-sqlserver – penartur Jun 26 '12 at 12:50
  • @MarcelPopescu BTW, the more I look on it, the less I like it. It seems to be very poorly written, and designed without the node ecosystem in mind (e.g. they implemented their own connection pooling). – penartur Jun 27 '12 at 04:26
  • Possible duplicate of [Node.js and Microsoft SQL Server](http://stackoverflow.com/questions/5156806/node-js-and-microsoft-sql-server) – Zephyr was a Friend of Mine May 26 '16 at 09:37

7 Answers7

29

This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.

At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.

"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.

On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.

If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE

Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js

Just in case, if the above links are not working, I am including the source code here:

var sql = require("mssql");

var dbConfig = {
    server: "localhost\\SQL2K14",
    database: "SampleDb",
    user: "sa",
    password: "sql2014",
    port: 1433
};

function getEmp() {
    var conn = new sql.Connection(dbConfig);
    
    conn.connect().then(function () {
        var req = new sql.Request(conn);
        req.query("SELECT * FROM emp").then(function (recordset) {
            console.log(recordset);
            conn.close();
        })
        .catch(function (err) {
            console.log(err);
            conn.close();
        });        
    })
    .catch(function (err) {
        console.log(err);
    });

    //--> another way
    //var req = new sql.Request(conn);
    //conn.connect(function (err) {
    //    if (err) {
    //        console.log(err);
    //        return;
    //    }
    //    req.query("SELECT * FROM emp", function (err, recordset) {
    //        if (err) {
    //            console.log(err);
    //        }
    //        else { 
    //            console.log(recordset);
    //        }
    //        conn.close();
    //    });
    //});

}

getEmp();

The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.

The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql

UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)

user203687
  • 6,875
  • 12
  • 53
  • 85
14

I am not sure did you see this list of MS SQL Modules for Node JS

Share your experience after using one if possible .

Good Luck

Futur
  • 8,444
  • 5
  • 28
  • 34
  • 2
    `tsqlftw` seems to be inactive; `node-mssql` is no longer available; `tedious` depends on `iconv` which uses `node-waf` which is not available on Windows, so it seems that i am left with the only choice of `tds`. At least today i was able to connect to DB with it, though i didn't perform any queries yet. – penartur Apr 25 '12 at 17:01
  • 1
    BTW, `iconv` is only optional for `tedious`, so currently i'm playing around with `tedious` (no serious things done yet though). `tds` did not work for me: https://github.com/cretz/node-tds/issues/25 – penartur Apr 26 '12 at 17:23
  • 1
    I'm using `tedious` at the moment, but, when i'll have some free time, i'll try to migrate to an official driver from MS that came out recently: https://github.com/WindowsAzure/node-sqlserver – penartur Jun 26 '12 at 12:51
  • official driver from MS seems to require a lot, including Visual Studio - so seems that cant be ran on Linux (?!). Tedious has good documentation and nice event model. playing w/ Tedious for now on a Windows (doesnt have Truestedconnection, BTW). – Lior Dec 12 '12 at 19:08
7

We just released preview driver for Node.JS for SQL Server connectivity. You can find it here: Introducing the Microsoft Driver for Node.JS for SQL Server.

The driver supports callbacks (here, we're connecting to a local SQL Server instance):

// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";

sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        for (var i = 0; i < results.rows.length; i++) {
            console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
        }
    });
});

Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):

// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";

var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });

If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
kop48
  • 505
  • 3
  • 8
  • 1
    +1 (and still active - yay!) but how does this help lock us in to Visual Studio/.NET-related products? Your marketing plans... they confuse me. – Erik Reppen Apr 04 '13 at 21:46
  • 1
    how do you close the db connections? – gjw80 Nov 05 '13 at 13:45
  • Great question. How are connections disposed? – Nathan Tregillus Jan 18 '14 at 08:33
  • The connection object returned from `open` has a `close` function defined as `function (immediately, callback)`, where `immediately` is optional. So in the first example above you'd call `conn.close(callback)` if you wanted it to finish up any operations before closing or `conn.close(true, callback)` to close immediately without waiting. – Joel May 16 '15 at 17:19
  • 3
    You should mention that this driver is **Windows only**. Very important. Also it's weird to start a blog post about using a library without mentioning the NPM install line. – jcollum Jul 14 '15 at 15:28
2

There is a module on npm called mssqlhelper

You can install it to your project by npm i mssqlhelper

Example of connecting and performing a query:

var db = require('./index');

db.config({
    host: '192.168.1.100'
    ,port: 1433
    ,userName: 'sa'
    ,password: '123'
    ,database:'testdb'
});

db.query(
    'select @Param1 Param1,@Param2 Param2'
    ,{
         Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
         ,Param2: { type : 'Int',value : 321 }
    }
    ,function(res){
        if(res.err)throw new Error('database error:'+res.err.msg);
        var rows = res.tables[0].rows;
        for (var i = 0; i < rows.length; i++) {
            console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
        }
    }
);

You can read more about it here: https://github.com/play175/mssqlhelper

:o)

Menztrual
  • 40,867
  • 12
  • 57
  • 70
  • 4
    Thank you for your answer, but being less than a month old, maintained by a single developer, containing a comments in Chinese doesn't make an impression of reliable production-grade library. Also, looking at the code, it seems that this `mssqlhelper` is really just a thin wrap layer over the `tds` library mentioned in previous questions on that matter. I'd like to hear about reliable well-maintained libraries (ideally, from Microsoft itself), not about the thin wrappers over the well-known libraries. – penartur Apr 25 '12 at 07:17
  • 2
    And, by the way, it seems that the author has also stolen the TDS package ( https://github.com/cretz/node-tds/tree/master/lib ) source code for their mssqlhelper, pretending that *play175* wrote it by themselves. – penartur Apr 25 '12 at 07:21
0

msnodesql is working out great for me. Here is a sample:

var mssql = require('msnodesql'), 
    express = require('express'),
    app = express(),
    nconf = require('nconf')

nconf.env()
     .file({ file: 'config.json' });

var conn = nconf.get("SQL_CONN");   
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";

app.get('/api/brands', function(req, res){
    var data = [];
    var jsonObject = {};    

    mssql.open(conn_str, function (err, conn) {
        if (err) {
            console.log("Error opening the connection!");
            return;
        }
        conn.queryRaw("dbo.storedproc", function (err, results) {
        if(err) {
                   console.log(err);
                   res.send(500, "Cannot retrieve records.");
                }
       else {
             //res.json(results);

             for (var i = 0; i < results.rows.length; i++) {
                 var jsonObject = new Object()
                 for (var j = 0; j < results.meta.length; j++) { 

                    paramName = results.meta[j].name;
                    paramValue = results.rows[i][j]; 
                    jsonObject[paramName] = paramValue;

                    }
                    data.push(jsonObject);  //This is a js object we are jsonizing not real json until res.send             
            } 

                res.send(data);

            }       
        });
    });
});
Neil Hoff
  • 2,025
  • 4
  • 29
  • 53
Buju
  • 93
  • 2
  • 9
0

Install mssql and express modules to execute this program

$ npm install express mssql

This example will allow you to connect with SQL Server and manipulate data from database

const sql = require("mssql");

const express = require("express");

const app = express();

app.get("/", (req, res) => {

    const config = {
        user: "<your_username>",
        password: "<your_password>",
        server: "<your_server_name>", //or ip address
        database: "<database_name>",
        options: {
            encrypt: true, // For secure connection
            trustServerCertificate: true,
        },
    };

    sql.connect(config, (err) => {
        if (err) {
            console.log(err);
        } else {
            console.log("{ db_Connected! }");
        }

        
        // Write queries here
        

    });
});


app.listen(4000, () => {
    console.log("app listening on port no:", 4000);
});

Following is the example for how can you write queries

// Query example
new sql.Request().query("SELECT * FROM <table_name>", (err, result) => {
     if (err) {
         console.log(err);
     } else {
         res.send(result);
         sql.close();
     }
 });
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Mar 15 '23 at 17:35
-2
//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000