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'
}
};
Related
I am unable to connect and retrieve my data from AWS RDS. I've used SQL Server Management Studio(SSMS) to do the manipulation of the data. I've stored my credentials in .env file. Below are my code:
.env
REACT_APP_API_KEY = 'my-secret-api-key'
RDS_HOSTNAME= 1001
RDS_USERNAME= Admi
RDS_PASSWORD = Password
RDS_PORT = 1041
dbConfig.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT
});
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
I am currently writing a database class that receives a node http request and saves data into a db.
It uses MSSQL (yeah...), therefore I'm using node-mssql.
I created a class to manage DB access, code:
"use strict";
var config = require('../../config/mainConfigs');
const mssql = require('mssql');
class db {
constructor(){
this._pool = null;
}
get_pool(){
if (!this._pool) {
if (config.Logging.DB.type == 'mssql'){
const dbOptions = {
user: config.Logging.DB.user,
password: config.Logging.DB.password,
server: config.Logging.DB.mssql.server,
database: config.Logging.DB.mssql.database,
options: {
encrypt: config.Logging.DB.encrypt
}
};
this._pool = new mssql.ConnectionPool(dbOptions);
}
}
return this._pool;
}
insertHTTPRequest(req){
const pool = this.get_pool();
if (config.Logging.DB.type == 'mssql'){
if (pool._connected){
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
return request.query(query);
}else{
return pool.connect().then(() => {
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
request.query(query);
}
}
}
}
I am using a middleware in the routes to save the request into the DB, like this:
app.use(function(req, res, next){
//send req to DB, get ID_SD_LOG from DB, assign to req.id
db_instance.insertHTTPRequest(req).then((genid)=>{
req.id = genid;
next();
}).catch((err)=>{
combinedLogger.error(err);
res.send('Database is unavailable.');
res.end();
})
});
Thing is, I am getting an error, however, in console, the error is undefined. So I really can't figure out whats wrong. I can imagine it's the connect() method, as I tested logging in console static string in the db request and I don't them, which I assume it's not even accessing that part.
Any help?
Thanks!
I use node typescript with mssql library to insert data into tables in my Azure server. I create a global connection pool, init it in the constructor then connect to it from route service. However, it shows the error
ConnectionError: Connection is closed at ActionService.insertion", "...at new ActionService", "... at new AppDataServices".
I don't know where broke down my logical connection between the global pool and route service. My SQL query might be wrong, but the main thing is about connection to the database.
Below is my code:
app-data-services.ts (global connection pool):
import * as mssql from 'mssql';
import { AppConfig } from '../config';
import { ActionService } from './data-services';
import { Logger, LoggerFactory } from '../common';
export class AppDataServices {
private static readonly LOGGER: Logger = LoggerFactory.getLogger();
private db: any;
public actionService: ActionService;
constructor(private appConfig: AppConfig) {
this.initConnectionPool();
this.actionService = new ActionService(this.db, AppDataServices.LOGGER);
}
private initConnectionPool() {
this.db = new mssql.ConnectionPool({
user: this.appConfig.mssqlUsername,
password: this.appConfig.mssqlPassword,
server: this.appConfig.mssqlServer,
database: this.appConfig.mssqlDatabase,
// If you are on Microsoft Azure, you need this:
options: { encrypt: true }
}, (err: any) => {
if (err) AppDataServices.LOGGER.error('MSSQL error', err);
});
}
}
action-service.ts (route data service):
import * as mssql from 'mssql';
import { Logger, LoggerFactory } from '../../../common';
export class ActionService {
private static readonly LOGGER: Logger = LoggerFactory.getLogger();
constructor (private db: any, private logger: any) {
this.insertion();
}
insertion() {
const request = new mssql.Request(this.db);
request.query(
`
INSERT INTO dbo.action
(timestamp, result, description, request_endpoint, request_payload, response_status, response_payload, actualAmount, rule_id, lendbook_id)
SELECT t1.start, 'SUCCESS', NULL, '/lendbook/usd', NULL, '200', NULL, t1.originalAmount, t1.id, t2.id
FROM dbo.rule t1, dbo.lendbook t2
INNER JOIN t2.id = t1.id
`, (err, result) => {
if (err) {
console.error(err);
return;
}
return result.recordsets[0];
});
}
}
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
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);
});