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:


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();

Comments

Post a Comment

Popular posts from this blog

Form submit resulting in “InvalidDataException: Form value count limit 1024 exceeded.” In ASP.NET Core

Repository Design Pattern in C#

Calculate Dynamic Current Calendar / Financial Year In C#