Connecting Node.js with SQL using MSSQL package

MongoDB is the preferred database for Node.js applications. Node.js can be used with other databases also.In this article we will see how to connect a Node.js application with Microsoft SQL server DB. First you should create a package.json file for your project. Create a new folder using the $mkdir {project folder name} command and type $cd{project folder name} to go into your project directory. Then execute the $npm init command and fill in necessary details. Now the package.json file will be created for you. You can now start installing your required packages. 

$ npm install mssql --save
$ npm install msnodesqlv8 --save

To connect SQL Server to your local server authentication is required. To make some necessary changes go to SQL Server Configuration Manager and make sure it is running and TCP/IP protocol is enabled. Set the port number to 1433. Navigate to SQL Server Network Configuration and click on protocol for SQLEXPRESS option. It will show TCP/IP protocol. Enable it and navigate to the Properties option of the same. Select the second tab which is IP Address->IPALL. Then set TCP Dynamic ports to Blank and set TCP port to 1433. Configurations are set and the app.js file will look like this.

const sql = require('mssql/msnodesqlv8')
//msnodesqlv8 module is required for Windows Authentication without using Username and Password

const pool = new sql.ConnectionPool({
  database: 'test-db',
  server: 'localhost',
  driver: 'msnodesqlv8',
  options: {
    trustedConnection: true
  }
})

pool.connect().then(() => {
  //simple query
  var queryString = 'select Top(1) Segment,Country,Product from Financial_Data';
  pool.request().query(queryString, (err, result) => {
    if(err)
    console.log(err)
    else 
        console.dir(result)
    })
})

Now run the $ node app.js command.