Created
June 6, 2017 14:49
-
-
Save steverhall/6a91148355456b3a651ec0a75f823cb1 to your computer and use it in GitHub Desktop.
Reading Azure SQL from Node.js backend using Tedious library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var Connection = require('tedious').Connection; | |
var Request = require('tedious').Request; | |
// Create connection to database | |
var config = { | |
userName: 'USERNAME', // update me | |
password: 'PASSWORD', // update me | |
server: 'DBSERVERNAME.database.windows.net', // update me | |
options: { | |
database: 'DATABASENAME', | |
encrypt: true, //you're going to want this | |
//rowCollectionOnRequestCompletion:true //only necessary if you want to retain rows after query complete. See NOTE below. | |
} | |
} | |
function queryDatabase(res){ | |
var connection = new Connection(config); | |
var result = []; | |
// Attempt to connect and execute queries if connection goes through | |
connection.on('connect', function(err) { | |
if (err) { | |
console.log(err) | |
} | |
else{ | |
var request = new Request( | |
"SELECT * FROM YOUR_TABLENAME", //update me | |
function(err, rowCount, rows) { | |
//NOTE: rows will not be populated unless rowCollectionOnRequestCompletion is set to true in config | |
console.log(rowCount + ' row(s) returned'); | |
res.json(result) | |
} | |
); | |
connection.execSql(request); | |
//For every row read, get column value and push to result | |
request.on("row", function (columns) { | |
var item = {}; | |
columns.forEach(function (column) { | |
item[column.metadata.colName] = column.value; | |
}); | |
result.push(item); | |
}); | |
} | |
}); | |
} | |
module.exports = { | |
get: function (req, res) { | |
queryDatabase(res) | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment