ExpressJS And SQL Server Connection with Instance Name

Known:

  • I installed SQL Server 2008
  • Instance name is SQLEXPRESS
  • Username: admin
  • Password: 4dmin
  • Database : master
  • Table : spt_values

Wanted:

I want to ExpressJS make connection to SQL Server 2008

Question:

How to do it … ?

Answer:

Start Two Service

  • SQL Server
  • SQL Server Browser

Install mssql

npm install mssql

Main Code (index.js)

var express = require('express');
var app = express();
var sql = require("mssql");

var config = {
        user: 'admin',
        password: '4dmin',
        server: 'localhost\\SQLEXPRESS', 
        database: 'master' 
		
    };
app.get('/data', function(req, res){
   // 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 top 5 * from spt_values order by name', function (err, recordset) {
            
            if (err) console.log(err)

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

app.listen(3000);

Result

Start the application with this command

node index.js

Open browser and write “http://localhost:3000/data” and the result like image below

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *