Connecting with SQL via. mssql npm module
suggest changeWe will start with creating a simple node application with a basic structure and then connecting with local sql server database and performing some queries on that database.
Step 1: Create a project directory. Initialize a Node.js application with npm init, which creates package.json in the current directory.
mkdir mySqlApp
# folder created
cd mySqlApp
# change to the new directory
npm init
# answer the questions
npm install
# finishes quickly because no packages have been added yet
Step 2: Create App.js in this directory and install the package used to connect to SQL Server.
npm install --save mssql
Step 3: Add a configuration object. The mssql module uses it to connect. For a local server without TLS, set encrypt to false or set trustServerCertificate to true.
var sql = require('mssql');
console.log("Hello world, This is an app to connect to sql server.");
var config = {
"user": "myusername", //default is sa
"password": "yourStrong(!)Password",
"server": "localhost", // for local machine
"database": "staging", // name of database
"options": {
"encrypt": true
}
}
sql.connect(config, err => {
if(err){
throw err ;
}
console.log("Connection Successful !");
new sql.Request().query('select 1 as number', (err, result) => {
//handle err
console.dir(result)
// This example uses callbacks strategy for getting results.
})
});
sql.on('error', err => {
// ... error handler
console.log("Sql database connection error " ,err);
})
Step 4: Start the application. It connects to SQL Server and prints the query result. console.dir(result) prints the driver's result object. The row is result.recordset[0] ({ number: 1 }), not the bare number 1.
node App.js
Hello world, This is an app to connect to sql server.
Connection Successful !
To run queries with promises or async/await, see the
mssqlpackage docs: