I am building an API integration application in Node.js using the "mssql" package. I have the data pulling from the third-party API, and stored in my SQL Server. However, my DB connection stays open forever and keeps my app running. Everything that I have tried ends the connection before the data can be stored. So, I can either store my data and keep the connection open forever, or end my connection and not store the data. The best that I have found is something like this answer: https://stackoverflow.com/a/45681751/5552707.
And I have tried that in my app, which still kills my connection before data is stored:
sql.connect(sqlConfig).then(pool => {
var request = new sql.Request(pool);
var result = request.bulk(table, (err, result) => {
if(err){
console.log("fail. " + err);
return;
}
})
}).catch(err => {
console.log('There was an error processing the request. ' + err);
}).then(() => {
console.log('done');
process.exit(1);
});
They docs don't explain how to do this, which is frustrating.
Any ideas would be awesome!
Thanks!
Adding
process.exit();
to the callback function did the trick.
var request = new sql.Request(pool);
var result = request.bulk(table, (err) => {
if(err){
console.log("fail. " + err);
return;
}
process.exit(1);
})
I'm trying to call a register stored procedure from SQL Server. I'm using NodeJS with the mssql package. I got most of the code from the mssql Npm documentation. But it still doesn't work.
The code basically tries to initiate a ConnectionPool as a read the last update renamed connection to ConnectionPool, create a new request, introduce the parameters and the execute the stored procedure. I have it this way because I need to change the connection variable to another database every once in a while.
The error I get is:
ConnectionError: Connection is closed.
My code:
const sql = require('mssql');
const config = require('../config/dbPoly');
module.exports.registerUser = function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario, callback) {
var connection = new sql.ConnectionPool(config);
var request = new sql.Request(connection);
request.input('input_parameter', sql.VARCHAR(25), pUserName);
request.input('input_parameter', sql.VARCHAR(16), pPassword);
request.input('input_parameter', sql.VARCHAR(25), pNombre);
request.input('input_parameter', sql.VARCHAR(50), pApellidos);
request.input('input_parameter', sql.Int, pFK_TipoUsuario);
request.execute('RegistrarUsuario', (err, result)=>{
if(err){
console.log(err);
}
else{
console.log(result);
}
});
};
There is this async version of implementation. Check if this serves your purpose
const sql = require('mssql');
const config = require('../config/dbPoly');
module.exports.registerUser = async function(pUserName, pPassword, pNombre, pApellidos, pFK_TipoUsuario) {
try {
let connection = await sql.connect(config)
let result = await connection.request()
.input('input_parameter', sql.VARCHAR(25), pUserName);
.input('input_parameter', sql.VARCHAR(16), pPassword);
.input('input_parameter', sql.VARCHAR(25), pNombre);
.input('input_parameter', sql.VARCHAR(50), pApellidos);
.input('input_parameter', sql.Int, pFK_TipoUsuario);
.execute('RegistrarUsuario');
return result;
} catch (err) {
console.log(err); // ... error checks
}
};
sql.on('error', err => {
// ... error handler
})
If someone else faces this problem, Prabodh's answer works perfectly.
I then faced another problem, it said the localhost was undefined in 1500ms. The reason was because my server field in the json config file had the following format: 'localhost\Server-Name'. I changed it just 'localhost' and problem fixed.
Also make sure your server has SQL Authentication enabled and not just Windows Authentication.
I am working on a MEAN application and I am trying to execute a job every X seconds that updates my DB. But, as first sprint, I am trying to launch a couple of queries just when I start express server (one for populate and another to list). Here is my code:
// set up ========================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
[....]
var Schema = mongoose.Schema;
// configuration =================
// connect to mongoDB database on localhost
var connection = mongoose.createConnection('mongodb://localhost/dv_db_admin');
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
console.info('connected to database dv_db_admin')
});
[...express stuff...]
// define model =================
var CountrySchema = new Schema({
name : String,
icaoCode : String,
documents : [String]
});
var Country = mongoose.model('Country', CountrySchema);
var country = new Country({
name : 'Afghanistan',
icaoCode : 'AFG',
documents : []
});
country.save(function(err, country) {
if (err) console.log("Error:",err);
console.log("Saved:",country);
});
console.log("After save");
Country.findOne({}, function(err, country) {
if (err) console.log("Error:",err);
console.log("Load:",country);
});
console.log("After find");
app.get('*', function(req, res) {
// load the single view file (angular will handle the page changes on the front-end)
res.sendfile('./public/index.html');
});
// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");
When I launch it, I have the following log output:
C:\Mercurial\DV-DB-Catalog>npm start
> dv-db-catalog#1.0.0 start C:\Mercurial\DV-DB-Catalog
> node server.js
After save
After find
App listening on port 8080
connected to database dv_db_admin
As you can see, there is no log about saved or list executions. I've run mongo shell and executed show dbs but it didn't appear.
Anybody knows what's happening?
Thanks in advance!
P.S.: I am running on background mongo service. When I start express server, Mongo log shows the following:
2016-04-15T12:00:50.876+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50766 #71 (3 connections now open)
2016-04-15T12:00:50.877+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50767 #72 (4 connections now open)
2016-04-15T12:00:50.878+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50768 #73 (5 connections now open)
2016-04-15T12:00:50.881+0200 I NETWORK [initandlisten] connection accepted from 127.0.0.1:50769 #74 (6 connections now open)
Try moving all of your calls to MongoDB in the connection.once callback. It looks like you are trying to save/load data from MongoDB before you have connected:
connection.once('open', function () {
console.info('connected to database dv_db_admin')
// define model =================
var CountrySchema = new Schema({
name : String,
icaoCode : String,
documents : [String]
});
var Country = mongoose.model('Country', CountrySchema);
var country = new Country({
name : 'Afghanistan',
icaoCode : 'AFG',
documents : []
});
country.save(function(err, country) {
if (err) console.log("Error:",err);
console.log("Saved:",country);
});
console.log("After save");
Country.findOne({}, function(err, country) {
if (err) console.log("Error:",err);
console.log("Load:",country);
});
console.log("After find");
});
I am using the angular fullstack generator, but I do not believe this is the problem. I am working with Stripe.js and trying to save the data to the SQLite database using Sequelize. I have tried many different things, but the server stops running when it gets to the part where it is supposed to save the data.
app.post('/register', auth.isAuthenticated(), function(req,res){
console.log('access: ',req.query)
var userId = req.body._id
var data = req.body.data
//create stripe acct for artists
stripe.accounts.create(data, function(err,acct){
if(err){
console.log('err!!! ', err)
} else {
console.log('acct: ', acct)
//look for user in database
db.User.find({
where: {
_id: userId
}
})
.then(function(user) {
if(user){
console.log('user: ', user)
//add stripe acct info to db
console.log('acct:', user.dataValues.account);
/*this is where the Server stops running*/
user.updateAttributes({
account: JSON.stringify(acct)
}).success(function(){
console.log('newacct:', user.dataValues.account);
//just to see if it works
res.send({'account': acct});
})
} else {
console.log('no user found bruh')
}
});
}
})
})
I have tried redirecting, changing req.method to 'get' and then res.redirect. res.end() all of the above, but it always stops running. No errors are thrown it just simply says 'Stopping Express Server'. Thanks in advance for the help!
Hi I'm unable to connect to SQL server that is using windows authentication in node js. I'm using the mssql module. The error message is :
[ConnectionError: Login failed for user ''. The user is not associated with a trusted SQL Server connection.]
name: 'ConnectionError',
message: 'Login failed for user \'\'. The user is not associated with a trusted SQL Server connection.',
code: 'ELOGIN' }
Here is my code:
config = {
server : "localhost\\MSSQLSERVER",
database : "mydatabase",
port : 1433
}
function loadDepts() {
var conn = new sql.Connection(config);
var request = sql.Request(conn);
conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
request.query("select deptid, deptname from departments", function(err, table) {
if (err) {
console.log(err);
return;
}
else {
console.log(table);
}
conn.close();
});
});
}
loadDepts();
Since this is a fairly visible answer, I wanted to add in a code snippet that worked for me with Trusted Connection. Got to it from getglad's edited answer.
const sql = require("mssql");
require("msnodesqlv8");
const conn = new sql.Connection({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
Using trusted connection, I was able to execute stored procedures, log the output, and close the connection without any trouble, and msnodesqlv8 has been updated more recently than any of the other drivers (latest release was October 2016 as of 11/3/2016), so that seems to be a safe choice as well.
And here's an example using mssql#4.0.4. The only changes are the initial require, which pull in msnodesqlv8 from within mssql, and sql.Connection is now sql.ConnectionPool. You will also need to change your stored procedure calls since the response is different, noted here. Credit to Jon's answer since he updated mine before I did!
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "db_name",
server: "server_name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then(() => {
// ... sproc call, error catching, etc
// example: https://github.com/patriksimek/node-mssql#request
});
I have been struggling too for some time about how to use mssql + Windows Auth, here is how i got it to work on my project.
As pointed out in the mssql documentation, you need msnodesqlv8 installed too.
npm install msnodesqlv8
Now, following on Aaron Ballard's answer, you use it like this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
database: 'database',
server: 'server',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
As a note, i tried to add this as a comment on Aaron's answer, as mine is just a complement/update to his, but i don't have enough reputation to do so.
I have never been able to get mssql + windows auth to work for any of my projects. Try edge and edge-sql - it has worked for me. Be sure you install all the required packages.
https://github.com/tjanczuk/edge
https://github.com/tjanczuk/edge-sql
From there, it's pretty steamlined.
var edge = require('edge');
var params = {
connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
source: "SELECT TOP 20 * FROM SampleData"
};
var getData = edge.func( 'sql', params);
getData(null, function (error, result) {
if (error) { console.log(error); return; }
if (result) {
console.log(result);
}
else {
console.log("No results");
}
});
EDIT
Well... 10 days after my original answer, apparently mssql added Windows Auth to the package. They heard our cries :) See here. I have not tested it yet, but it is officially in my backlog to test integration. I will report back.
FWTW, if mssql fits your needs, I would go with it, as 1) edge-sql has been dormant for 2 years and 2) the primary contributor has said he has left projects like this "in the caring hands of Microsoft", since he no longer works there.
EDIT 2
This keeps getting upvotes and there are comments saying some of the other answers' code examples either aren't working or aren't working on Windows.
This is my code using mssql, working on Windows, with msnodesqlv8 also installed:
var sql = require('mssql/msnodesqlv8');
var config = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client XX.0};Server={SERVER\\NAME};Database={dbName};Trusted_Connection={yes};',
};
sql.connect(config)
.then(function() {
...profit...
})
.catch(function(err) {
// ... connect error checks
});
I've tried many variations and this is my complete solution.
I'm using SQL server Express.
I'm connecting, in the first instance, to the MASTER database only.
You only NEED to change "YOURINSTANCE\\SQLEXPRESS".
(Be sure to maintain the double-slash above!!!)
I'm using INTEGRATED SECURITY too.
The query relies on nothing at all (in your database).
You need to add your node packages
==> NPM INSTALL MSSQL and
==> NPM INSTALL msnodesqlv8
Hopefully, your connection issues will be a thing of the past.
Maybe.
Please.
// More here -> https://www.npmjs.com/package/mssql
var sql = require('mssql/msnodesqlv8');
var config = {
connectionString: 'Driver=SQL Server;Server=YOURINSTANCE\\SQLEXPRESS;Database=master;Trusted_Connection=true;'
};
sql.connect(config, err => {
new sql.Request().query('SELECT 1 AS justAnumber', (err, result) => {
console.log(".:The Good Place:.");
if(err) { // SQL error, but connection OK.
console.log(" Shirtballs: "+ err);
} else { // All is rosey in your garden.
console.dir(result);
};
});
});
sql.on('error', err => { // Connection borked.
console.log(".:The Bad Place:.");
console.log(" Fork: "+ err);
});
For me
I used connection setting as below
"server":"",
"domain":"", //sepcify domain of your user
"port": ,
"user":"", // enter username without domain
"password":"",
"database":""
and the TS code
import * as sql from 'mssql';
const pool = await new sql.ConnectionPool(connection).connect();
const result = await pool.request()
.query(`SELECT count(idpart) part_computed FROM demo.PARTs;`);
pool.close();
return Promise.resolve(result.recordset);
I could only get a Trusted Connection working using msnodesqlv8 (limited to Windows environments) with a connection string (rather than a config object).
const sql = require("msnodesqlv8");
const connectionString = function(databaseName) {
return "Server=.;Database=" + databaseName + ";Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
}
sql.query(connectionString("DatabaseName"), "SELECT * FROM dbo.Table1" , (err, recordset) => {
if(err) {
// Do something with the err object.
return;
}
// else
// Do something with the recordset object.
return;
});
Below code is working for me......
const sql = require('mssql/msnodesqlv8')
// config for your database
var config = {
driver: 'msnodesqlv8',
server: 'serverNAme\\SQLEXPRESS',
database: 'Learn' ,
options: {
trustedConnection: true
}
};
It worked for me
need to install msnodesqlv8 and mssql. also .......:)
var dbConfig = {
driver: 'msnodesqlv8',
server: "DESKTOP-66LO4I3",
database: "FutureHealthCareWeb",
user: "sa",
password: "pass#123",
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
var sql = require('mssql/msnodesqlv8');
sql.connect(dbConfig, function (err) {
if (err) { console.log(JSON.stringify(err)+'..............') }
else {
console.log('Connected')
}
}
);
this worked for me
const sql = require("mssql/msnodesqlv8");
const conn = new sql.ConnectionPool({
database: "DB name",
server: "server name",
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
});
conn.connect().then((err) => {
if(err) throw err;
else console.log("connected");
const req = new sql.Request(conn)
req.query("select * from table", function(error, res){
console.log(res)
})
});
I struggled to connect with mssql server which run in remote windows server using windows authentication mode . Then i found the solution just used like below code.
sql.connect("Data Source=172.25.x.x,1433;User Id=CSLx\\Name;Password=xxxxxx1234;Initial Catalog=giveTHedataabseNamel;Integrated Security=True",function(err){ }
I've just add domain: "DNAME", in config, and as result this config helps me connect to MS SQL with windows auth.
const config = {
driver: 'msnodesqlv8',
domain: "DNAME",
user: 'username',
password: 'pass',
server: '7.6.225.22',
database: 'DBNAME',
requestTimeout: 3600000, //an hour
options: {
trustedConnection: true
},
debug: true,
parseJSON: true
};
This version doesn't need a username or password.
To use windows authentication I installed mssql and msnodesqlv8.
Then in my app.js file:
const mssql = require('mssql/msnodesqlv8');
Note it is mssql not sql if you're using this example.
var config = {
database:'YOUR DATABASE NAME',
server: 'localhost\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
enableArithAbort: true
}
};
You need to change the database name in config. Other than that it should work. My example:
app.get('/', function (req, res) {
mssql.connect(config, function (err) {
if (err) console.log(err);
var request = new mssql.Request();
request.query('select * from dbo.visit', function (err, result) {
if(err) console.log(err);
console.log(result);
});
});
});