How do I connect my database to local SQL Server Express using nose js - sql

I am using Express framework and trying to connect to my SQL Server Express database locally. I am getting error - connection failure. I need help with that, if you'd please.
Steps completed so far..
npm install mssql
var sql = require("mssql");
// config for your database
var config = {
user: 'ImacamUser',
password: '*****',
server: 'localhost',
database: 'InvoicingData'
};
sql.connect(config, (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 Customers', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
The error I get from this code is:
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at C:\Projects\RCN\Invoicing\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1012:9)
at Object.onceWrapper (node:events:510:26)
at Connection.emit (node:events:390:28)
at Connection.emit (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1040:18)
at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:12)
at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:28)
at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
code: 'ESOCKET',
isTransient: undefined
}
Any help would be appreciated.

Related

Connect to Databricks SQL endpoint using NodeJS

I am trying to connect to a Databricks SQL endpoint using NodeJS. I followed the instructions on the "Connection Details" tab of my SQL endpoint. As described, I am running Node version 14 or higher, and installed the connector npm package as follows:
npm i #databricks/sql
I used the code provided, included below (I made sure to use the correct host name and access token). I did not change the SQL code from the default (SELECT 1).
const { DBSQLClient } = require('#databricks/sql');
var token = "dapi_MY_ACCESS_TOKEN";
var server_hostname = "MY_HOSTNAME.cloud.databricks.com";
var http_path = "/sql/1.0/endpoints/a8e8b6cfcc6a190f";
const client = new DBSQLClient();
const utils = DBSQLClient.utils;
client.connect(
options = {
token: token,
host: server_hostname,
path: http_path
}).then(
async client => {
const session = await client.openSession();
const queryOperation = await session.executeStatement(
statement = "SELECT 1",
options = { runAsync: true });
await utils.waitUntilReady(
operation = queryOperation,
progress = false,
callback = () => {});
await utils.fetchAll(
operation = queryOperation
);
await queryOperation.close();
const result = utils.getResult(
operation = queryOperation
).getValue();
console.table(result);
await session.close();
client.close();
}).catch(error => {
console.log(error);
});
When I run the code, I get the following error message:
node read_databricks.cjs
TypeError: Cannot read properties of undefined (reading 'waitUntilReady')
at /Users/vijay.balasubramaniam/test/records-to-cards/read_databricks.cjs:23:19
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I also tried running the above code within the node REPL, but got the same results. Am I missing a step?
I ran into the same issue.
Delete your package-lock.json. Run npm install and make sure that in the package-lock.json file the version is pointing to beta.1 and not beta.2.
"node_modules/#databricks/sql": {
"version": "0.1.8-beta.1",
}

Trying to connect to sql server from an electron app but port not found error

I am trying to connect to sql server from an electron app :
const sql = require('mssql');
const config = {
server: 'localhost\\DESKTOP-N83KUSU',
user: 'ashraf1',
password: 'password',
database: 'sampleDB',
port: 1433,
options: {
trustedConnection: true,
}
};
function connectToServer(){
sql.connect(config, (err)=> {
if(err) {return console.log(err)}
console.log('connected');
})
}
connectToServer();
but I get this error:
I have enabled TCP/IP and SQL server Browser is running. I searched a lot but didn't find a solution that works. Any idea on how to solve this?
server should be localhost, remove the system name.
server: 'localhost',

How to connect an existing nodejs server app to Azure SQL database

Can anyone please advise:
I have an existing nodejs server running on azure, running node 10.14 on Linux. The project code is on github and when I push changes they are automatically pushed to azure.
I have set up a database server and database though the Azure portal and can query it through the Azure portal.
I want to modify the nodejs server to conect to the database, I have the connection string code etc. but just the act of adding the line:
var mysql = require('mysql');
will stop the server form running as presumably I have not installed mysql on the machine which is running the server in the Azure cloud.
How can I get this to work?
Thanks for any help,
Mitch.
According to the error, you do not add the package in your package.json file and install the package in your project. Besides, if you want to connect Azure SQL server database, we can use package mssqql
For example
My package.json file
{
....
"dependencies": {
"express": "^4.17.1",
"mssql": "^6.2.0",
"request": "^2.88.2"
}
}
code
const router = express.Router()
const sql = require('mssql')
const config = {
user: "<user name>",
password: "<password>",
server: "<your SQL server name>.database.windows.net",
port: 1433,
database: "test",
connectionTimeout: 3000,
parseJSON: true,
options: {
encrypt: true,
enableArithAbort: true
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
};
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();
router.get('/', async function (req, res) {
await poolConnect;
try {
const request = pool.request();
const result = await request.query('select 1 as number')
console.log(result);
res.json(result.recordset);
} catch (err) {
console.error('SQL error', err);
res.send(err);
}
});
Test.

Azure SQL database is not updating with data

I have created a nodejs azure web app and it is running perfectly fine,
Now I want to get my post data to azure MS SQL DB, I have created a code for that, however sql db is not updating with POST data, can anyone help me with this.
var express = require('express');
var bodyParser = require('body-parser');
var sql = require('mssql');
var port = 8080;
var app = express();`enter code here`
var path = require('path');
//CORS Middleware
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,OPTIONS");
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,contentType,Content-Type,Accept,Authorization");
next();
});
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
//setup database connection
var dbconfig = {
user:"username",
password:"password",
server : "server_name",
database: "db_name"
};
// ConnectionPool
//connect to the database
var executeQuery = function(res,query){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// query to the database
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}
app.get('/', function(req, res){
res.render('index', {
title: 'Hello World',
showTitle:true,
people: ['John', 'Steve', 'Jose']
});
});
app.get('/index', function(req, res){
res.render('index');
});
app.get('/contact', function(req, res){
res.render('contact');
});
app.post('/my_user', function(req, res){
//return res.send(req.body);
console.log(req.body.email + ' and ' + req.body.mobile);
var parameters = [
{ name: 'email', sqltype: sql.NVarChar, value: req.body.email},
{ name: 'mobile', sqltype: sql.NInt, value: req.body.mobile},
{ name: 'msg', sqltype: sql.NVarChar, value: req.body.msg},
];
var query = "insert into forMyCV values(#email, #mobile, #msg);";
executeQuery (res, query, parameters);
return res.redirect('/');
});
app.listen(port);
console.log('Server started on port '+port);
can anyone help me with this explain this to me. why this is happening
I'm afraid there are two issues in your code after I had test it.
According to the tab Connection strings of your Azure SQL Database on Azure portal as the figure below, there is a required parameter encrypt=true in the connection string like for JDBC and others, too.
So the correct config for Azure SQL Database using mssql should be as below.
const config = {
user: '<your username>#<your sql server name>',
password: '<your password>',
server: '<your sql server name>.database.windows.net', // You can use 'localhost\\instance' to connect to named instance
database: '<your database name>',
options: {
encrypt: true // Use this if you're on Windows Azure
}
}
The required options: {encrypt: true} property can not be ignored. Otherwise, it will cause the error.
there is a database connection error -> ConnectionError: Server requires encryption, set 'encrypt' config option to true.
(node:665784) UnhandledPromiseRejectionWarning: ReferenceError: res is not defined
at D:\projects\node\express-demo\mssql-query-demo.js:43:13
at _poolCreate.then.catch.err (D:\projects\node\express-demo\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:665784) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:665784) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
the executeQuery function is defined with two parameters res and query, but it be used with three parameters executeQuery (res, query, parameters); in the callback function(req, res) of app.post('/my_user'). It will not cause any error and just ignore the nonmatched last parameter parameters.
Hope it helps.
Update: Redefine the executeQuery function as below.
var executeQuery = function(res,query, parameters){
sql.connect(dbconfig,function(err){
if(err){
console.log("there is a database connection error -> "+err);
res.send(err);
}
else{
// create request object
var request = new sql.Request();
// query to the database
parameters.map(item => {
request.input(item.name, item.sqltype, item.value);
})
request.query(query,function(err,result){
if(err){
console.log("error while querying database -> "+err);
res.send(err);
}
else{
res.send(result);
sql.close();
}
});
}
});
}

Node trusted connection using msnodesqlv8

I'm trying to connect to SQL server using msnodesqlv8 driver. Now I'm getting an error (TypeError: sql.connect is not a function) before I try to connect with msql driver and I got response but I really need to use a trusted connection.
my code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("msnodesqlv8");
console.log(sql);
// config for your database
var config = {
server: 'sqlServername',
database: 'myTestDatabase',
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
};
// 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 myTable', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Is there any other driver I can use trusted connection?
I'm using sql server 12.0.4237.0
I try this as well
const sql = require('mssql/msnodesqlv8');
const config = {
user: "xxxxxxxx",
password: "xxxxxxxxx",
domain: "xxxxxxx.com",
server: 'hubuddb66',
database: 'KSheduler',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
trustedConnection: true
}
}
sql.connect(config)
.then(conn => console.log("Success!"))
.catch(err => console.log("error! " + err));
I receive this error:
ConnectionError: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'domainxxx\userxxxx'.
Read the documentation; there is no such function.
You're looking for sql.open().
If you're trying to connect to MySQL server you can use Sequelizejs you can find the documentation here, If you're trying to connect to MSSQl using msnodesqlv8 you can use sql.open(connStr, callback(err, conn)). you can find examples here.
In both cases make sure your MySQL or MSSQL servers are running.
You can also use Sequelizejs to connect to MSSQL.
For me changing this condition from 'No' to 'Yes' worked:
switch (key) {
case 'instance':
return this.config.options.instanceName
case 'trusted':
return this.config.options.trustedConnection ? 'Yes' : 'Yes'
It just doesn't load the value from the options object even if I provide it.
I hardcoded this change in file \node_modules\mssql\lib\msnodesqlv8\connection-pool.js