Skip to content

Instantly share code, notes, and snippets.

@martinacostadev
Last active July 23, 2020 19:56
Show Gist options
  • Save martinacostadev/6791a22fe3389908a88554943b814fc0 to your computer and use it in GitHub Desktop.
Save martinacostadev/6791a22fe3389908a88554943b814fc0 to your computer and use it in GitHub Desktop.
node express sql server / Connect to SQL Server, run script and show in web with NodeJS
/*
Connect to SQL Server, run script and show in web with NodeJS
Commands:
npm init
npm install
npm install express
npm install mssql
node index.js
open in browser: localhost:5000
*/
/* index.js */
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
var config = {
user: 'sa',
password: 'PASSWORD',
server: 'LOCALHOST',
database: 'DATABASENAME',
options: {
"encrypt": false,
"enableArithAbort": true
},
pool: {
min: 1,
max: 100,
idleTimeoutMillis: 30000
}
};
sql.connect(config).then(() => {
var request = new sql.Request();
// query to the database and get the records
request.query('select * from [DATABASENAME].[dbo].[TABLENAME] where [FIELDNAME] = 1', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
}).then(result => {
console.dir('Result: ', result)
});
sql.on('error', err => {
console.dir(err)
})
});
var server = app.listen(5000, function () {
console.log('Server is running...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment