Error while running node-mssql query - sql-server

I am trying to run node-mssql query, if I run simple quires it is getting executed. But when I use OPENROWSET and Microsoft.ACE.OLEDB.12.0, it is showing some errors.
Here is server.js code
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: '..',
password: '....',
server: 'localhost\\SQLEXPRESS',
database: 'test_databasae'
};
// connect to your database
sql.connect(config, function (err) {
if (err)
console.log(err);
else
console.log("Connection successful");
// create Request object
var request = new sql.Request();
// query to the database and get the records
/*request.query('select * from table1', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});*/
request.query('INSERT INTO [mytable](SalesPersonID,TerritoryID)' +
'SELECT SalesPersonID,TerritoryID FROM OPENROWSET(' +
'\'Microsoft.ACE.OLEDB.12.0\',\'Excel 12.0\';\'Database=D:\\sample\\test\\data\\1540_OPENROWSET_Examples.xls;,\'' +
'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$])',function(err,recordset){
if(err) console.log(err)
console.log("success");
});
});});var server = app.listen(5000, function () {
console.log('Server is running..');});`
and when i hit node server.js on command prompt I am getting following errors on command prompt:
Server is running..
Connection successful
{ [RequestError: Incorrect syntax near ')'.]
name: 'RequestError',
message: 'Incorrect syntax near \')\'.',
code: 'EREQUEST',
number: 102,
lineNumber: 1,
state: 1,
class: 15,
serverName: 'localhost\\SQLEXPRESS',
procName: '',
precedingErrors:
[ { [RequestError: Incorrect syntax near the keyword 'SELECT'.]
name: 'RequestError',
message: 'Incorrect syntax near the keyword \'SELECT\'.',
code: 'EREQUEST',
number: 156,
lineNumber: 1,
state: 1,
class: 15,
serverName: 'localhost\\SQLEXPRESS',
procName: '' } ] }
success
The same query is getting executed in SQL Server Management Studio , it is successfully inserting excel data to database.Excel sheet data looks like this:
SalesPersonID TerritoryID
-------- -----------
275 2
276 4
277 3
Here is the plunker link

I see few syntax errors in your code:
Sample code for OPENROWSET is:
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;HDR=YES', 'SELECT * FROM [Sheet1$]')
In your code extra ' between the Excel and Database keywords ,\'Excel 12.0\';\'Database=D:\\sample ..., that need to correct
The SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$] need ' before and after.
So your working code will be:
request.query('INSERT INTO [mytable](SalesPersonID, TerritoryID)' +
' SELECT SalesPersonID, TerritoryID FROM OPENROWSET(' +
'\'Microsoft.ACE.OLEDB.12.0\', \'Excel 12.0;Database=D:\\sample\\test\\data\\1540_OPENROWSET_Examples.xls;HDR=YES\', ' +
'\'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$]\')',function(err,recordset){
if(err) console.log(err)
Update :
The OP received this configuration error:
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error.
To fix the configuration error, the below script need to execute:
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

Related

How to execute stored procedure from Nodejs

I have this router in nodejs and I want to execute a stored procedure:
router.post('/upadateCreateSiteMonth', isAuthed, function(req, res) {
//console.log('REQ USER', req.user);
var q = 'USE [EYE]' +
'GO' +
'DECLARE #return_value int' +
'EXEC #return_value = [dbo].[uspCreateSiteMonthConsumption]' +
'SELECT \'Return Value\' = #return_value' +
'GO'
exp.emitter.emit('mssql',{ q: q}, function(err, data) {
if (err) {
res.status(500).json({ error : err });
} else {
res.status(200).json(data);
}
});
});
When I write this in SQL Server database it is ok
DECLARE #return_value INT
EXEC #return_value = [dbo].[uspCreateSiteMonthConsumption]
SELECT 'Return Value' = #return_value
GO
How can I write the variable q to respond with 200 this router?
A simple query like Select * from table works ok, but when I try to use this query to run the stored procedure, I get a response of 500.

unable to connect to ms sql window authetication using node js

Here is my node js code
app.get('/', function (req, res) {
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userform', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
});
Please suggest me to connect sql and getting this error after running this in command prompt
Server is running.. on Port 8020
{ Error: Failed to connect to localhost:undefined in 15000ms
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:12)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
code: 'ETIMEOUT',
originalError:
{ ConnectionError: Failed to connect to localhost:undefined in 15000ms
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:28)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
message: 'Failed to connect to localhost:undefined in 15000ms',
code: 'ETIMEOUT' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:118:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
undefined
This might help :
Start the "SQL SERVER BROWSER" Service in Windows services (I've configured it to start automatically)
allow SQL Server Express to accept remote connections over TCP/IP for port 1433 : http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote-tcp-ip-connections-on-port-1433.aspx
Finally restart 'SQL Server' and 'SQL Browser Agent' services
Installing mssql package I had a similiar problem and I got fixed addiyng an instance and database name to my config.
I thought it was better create an user on db.
After I need to handling the errors, addiyng try catch to my function that will connect in db and closing the connection if the function get an error.
All database connections are in a different file, so I export the modules to use in my application and if I need to use in other application just add a reference to that
let QueryDB = {
Query_SelectAll: 'SELECT [COLUMN] \
, [COLUMN] \
, [COLUMN] \
FROM [DATABASE].[dbo].[TABLE_NAME]',
Query_Delete: 'DELETE FROM [DATABASE].[dbo].[TABLE_NAME] WHERE COLUMN = '
};
I put all queries in an object to simplify the use for me.
let ConnectionString = {
user: 'YOUR_DBUSER',
password: '****',
server: '0.0.000.00',
options: {
instance: 'YOURINSTANCE',
database: 'DATABASE_NAME'
}
};
In the server property, I put the server IP, after add the options with instance and database name.
function SQL_Server(Query, ret) {
sql.close();
sql.connect(ConnectionString).then(() => {
console.log("Connected");
return request(Query, ret);
}).catch((error) => {
console.log("Connect error");
console.error(error);
sql.close();
});
}
function request(Query, ret) {
let returning = undefined;
let request = new sql.Request();
(request.query(Query).then((recordset) => {
sql.close();
returning = recordset.recordset;
}).catch((error) => {
console.error(error);
sql.close();
})).then(() => {
if (ret != undefined)
ret(returning);
console.log("Successful object return");
});
}
Those are my connect and request functions.
module.exports.SQL_Server = SQL_Server;
module.exports.QueryDB = QueryDB;
So I export the modules to use the functions.
An example of using:
let DataBase = require("./Connection_Query");
let FuncSql = DataBase.SQL_Server;
let SQL = DataBase.QueryDB;
APP.get(ProjectName + '/Home', (req, resp) => {
FuncSql(SQL.Query_SelectAll, (rec) => {
resp.render("Home", { YourObjects: rec });
});
});
Think that you use this answer to guide you.
you have to write the database instance in config.options.instanceName
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
instead:
const config = {
user: '...',
password: '...',
server: 'localhost',
database: 'TestingDB',
options: {
encrypt: false, // Use this if you're on Windows Azure
instanceName: 'SQLEXPRESS2008'
}
};

What is the node.js equivalent of this T-SQL query

The legacy system used to store passwords in query's output format,
SELECT
HASHBYTES('SHA1', CONVERT(VARCHAR, HASHBYTES('SHA1', CONVERT(NVARCHAR(4000), ’test'))) + 'mysalt')
where the password is test and mysalt is the salt used.
The result is something like
0x169A0EF01AA369518D6810E14872A3A003A1F0AA
I have to take that encrypted password and create a node function to get the same result as the above query
Node.js is not going to replace a t-sql query. You would still use t-sql to query your database and something like the tedious module connection to the database. This is an example from https://msdn.microsoft.com/library/mt715784.aspx on how to connect from node.js to SQL Server and execute a query. Some modifications to the executeStatement function would get you going.
var Connection = require('tedious').Connection;
var config = {
userName: 'yourusername',
password: 'yourpassword',
server: 'yourserver.database.windows.net',
// When you connect to Azure SQL Database, you need these next options.
options: {encrypt: true, database: 'AdventureWorks'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("SELECT c.CustomerID, c.CompanyName,COUNT(soh.SalesOrderID) AS OrderCount FROM SalesLT.Customer AS c LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID GROUP BY c.CustomerID, c.CompanyName ORDER BY OrderCount DESC;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}

How to use select statement with where condition on node.js

> Am trying to provide login credentials with email and password using postgres database table.
postgres database tables. When i get records it should send 200 status
to my page.Am getting error on query. Kindly help me out how to use
select with where condition. Am missing some syntax.
getUser : function(req, res) {
var pg = require('pg');
var conString = process.env.DATABASE_URL || "postgres://test:test#localhost:5432/wallet";
var client = new pg.Client(conString);
client.connect();
console.log(req.query.email_id);
console.log(req.query.user_password);
var query = client.query("select * from pp_user_profile where email_id ="+req.query.email_id+ "and" + "user_password=" +req.query.password);
query.on("end", function (result) {
client.end();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Success');
res.end();
});
},
Try the below syntax:
"select * from pp_user_profile where email_id = '"+req.query.email_id+"' and user_password= '"+req.query.password+"'";

Connection to table denied in SQL Server 2012

I am trying to manipulate a table in SQL Server with node. I've succeeded to connect to the database but when I do a query request I get this error :
SELECT permission was denied on the object Customer
I've tried this command but it didn't work :
USE NodeDB;
GRANT SELECT ON OBJECT::Customer TO test;
GO
This is the code I've written in node :
/*--------------------Connection--------------------------------*/
var sql = require('mssql');
var config = {
user: 'test',
password: '11111',
server: 'ICEFOX-PC\\SQLSQL',
database: 'NodeDB'
}
sql.connect(config, function(err) {
if (err){
throw err ;
} else{
console.log('connected');
}
/*--------------------Connection--------------------------------*/
var request = new sql.Request([config]);
request.query('select * from Customer', function(err, recordset) {
if (err) {
throw err ;
} else {
console.dir(recordset);
});

Resources