How to connect MSSQL database using JavaScript – 2 examples

SQL Database validations using Tedious, MSSQL are very important for database connection and validation test automation so we have created some connection methods to connect to database and execute a query using Tedious and mssql packages. Read further to know How to connect mssql database using Javascript with the help of an example.

This  returns data from database and that can be used further for any assertion in database testing automation.  This is just a sample database connection and validation. You can change it to suite your requirement. 

These code blocks are tested with real database connections so you can copy and reuse them after making some changes at identified places for javascript mssql database connection example.

How to connect mssql database using Javascript – Example 1
var sql = require('mssql');
//2.
var config = {
    server: 'server.address.net',//change server address here
    database: 'dbname',//change db name here
    user: 'adminbot',//change user here
    password: 'bot@1234',//change password here
    port: 1433,//change port here
    encrypt: true
};
//3.

function getResult() {
    loadEmployees();
}
function loadEmployees() {
    //4.
    var dbConn = new sql.ConnectionPool(config);
    //5.
    dbConn.connect().then(function () {
        //6.
        var request = new sql.Request(dbConn);
        //7.
        request.query("select * from employees").then(function (recordSet) {
            // console.log(recordSet);
            console.log(recordSet.Fields('Name').value);

            return recordSet;
            dbConn.close();
        }).catch(function (err) {
            //8.
            console.log(err);
            dbConn.close();
        });
    }).catch(function (err) {
        //9.
        console.log(err);
    });
}
//10.
getResult();
How to connect mssql database using Javascript – Example 2
var sql = require('mssql');

var config = {
	server: 'db.server.net',//change server address here
	database: 'db',//change db name here
	user: 'adminbot@db',//change username here
	password: 'bot@1234',//change password here
	port: 1433,//change port here
	options: {

		encrypt: true
	}
};

function getQueryResults(myquery) {

	var conn = new sql.ConnectionPool(config);
	var req = new sql.Request(conn);

	await conn.connect(function (err) {
		console.log('in connect');
		if (err) {
			console.log(err);
			return;

		}
		req.query(myquery, function (err, recordset) {
			console.log('in query');
			if (err) {
				console.log(err);
			}
			else {
				console.log('in recordset');
				console.log(recordset);
				//return recordset;
			}
			conn.close();
		});

	});

};

You may also read

Similar Posts

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.