How to connect to SQL Server database using Node.Js
Description
- A quick overview on SQL Server configuration, in order to get connected through Node.Js
- Using "mssql" npm package to connect to SQL Server using Node.Js
- How to use "Connection" object to connect to SQL Server
- How to use "Request" object to execute SELECT statement and fetch results
- How to handle SQL Server Connection Errors (from Node Js)
- How to handle SQL statement execution Errors (from Node Js)
Source Code:
varsql = require("mssql");
vardbConfig = {
    server: "localhost\\SQL2K14",    database: "SampleDb",    user: "sa",    password: "sql2014",    port: 1433
};
functiongetEmp() {    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(); 
Nice post. Thanks for sharing.
ReplyDeleteSQL training in Pune