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

What is the importance of EDMX file in Entity Framework

TRIGGER in sql server

Sending Email in asp.net or mvc using gmail or other smpt.