Connecting to MSSQL server with Sequelize - javascript

Using the following tedious code, I can successfully connect to an Azure SQL Server.
const Connection = require('tedious').Connection;
const connection = new Connection({
userName: '[USER]',
password: '[PASSWORD]',
server: '[HOSTNAME]',
options: {encrypt: true}
});
connection.on('connect', (err) => {
if (err) {
console.log('error connecting', err);
} else {
console.log('connection successful');
}
});
However, using what should be the equivalent Sequelize code, I get a connection timeout error.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('[DBNAME]', '[USER]', '[PASSWORD]', {
dialect: 'mssql',
host: '[HOSTNAME]',
dialectOptions: {
encrypt: true
}
});
sequelize.authenticate().then((err) => {
console.log('Connection successful', err);
})
.catch((err) => {
console.log('Unable to connect to database', err);
});
Any thoughts?
Using: sequelize 3.29.0, tedious 1.14.0, SQL Server v12

I was getting below error
SequelizeConnectionError: Server requires encryption, set 'encrypt' config option to true.
I tried it out with Azure SQL Database and below way is working for me.
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});

If you're trying it out with Azure SQL Database, you might also want to specify a longer request timeout value:
[...]
dialectOptions: {
requestTimeout: 30000 // timeout = 30 seconds
}
[...]

I tried your Sequelize code and it works fine. So you might need to add Client IP address to allow access to Azure SQL Server. To do this, go to the Azure portal, click on All Resources, select your SQL server, click on Firewall in the SETTINGS menu.
Your client address is conveniently included in the list, so you can just click on Add client IP followed by Save. When you run your code now, it should connect.

if you are using sql server management studio then simply replace dialect:'mysql' with dialect:'mssql':
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});

Related

MariaDB NodeJS backend : too many connections

I have a NodeJS express backend which uses a MariaDB database.
My file dbconnect.js creates a mariadb pool and has a function to make queries.
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret
});
const dbQuery = async(query) => {
let conn;
let res = '';
try {
conn = await pool.getConnection();
res = await conn.query(query);
} catch (err) {
console.log("Error sending Query: ", query, err.text);
} finally {
if (conn) {
conn.end();
}
return res;
}
}
Everything seems to work perfectly, but after a few months with the server running these messages begin to appear on the console:
These messages keep appearing every 10-14 seconds, but no queries are being performed.
Thanks for any help
I am not sure but there is one way,
configure your connection pool to ping at particular time. so it will close any inactive connections before the server closes them. mariadb has pingInterval for this
Replace this code with your code
const pool = mariadb.createPool({
host: process.env.DBHost,
user: process.env.DBUser,
database: process.env.DB,
password: process.env.DBSecret,
pingInterval: 60000
});
This will send a ping to the server every 60 seconds, which will prevent the server from closing inactive connections.

Knex.js connection error when rerunning the function

I'm using Knex to connect to an Azure database, run a query that returns the status of a database (COPYING/ONLINE).
If I run this once, all is fine.
But if I use a setInterval to rerun this (I want to know when the status changes from COPYING to ONLINE) I'm getting a connection error the second, and third, and.. time the function is called.
Here is my code
const knex = require('knex')({
client: 'mssql',
connection: {
host: '***',
user: '***',
password: '***',
options: { requestTimeout: 350000, encrypt: true },
},
pool: {
min: 0,
max: 15,
},
});
async function copyStatus() {
try {
console.log('Running query');
const status = await knex.raw(
"SELECT name, state_desc FROM sys.databases WHERE name = 'Tide_QA_Dev_runtime' "
);
return status[0].state_desc;
// console.log(status[0].state_desc);
} catch (error) {
console.log(error);
} finally {
console.log('Closing connection with database');
await knex.destroy();
}
}
function intervalFunc() {
copyStatus().then(function (result) {
if (result === 'ONLINE') {
console.log('Database copy is done.');
} else if (result === 'Database is still copying') {
console.log('bezig');
}
});
}
setInterval(intervalFunc, 2000);
Here is my output
Closing connection with database
Database copy is done.
Running query
Error: Unable to acquire a connection
at Client_MSSQL.acquireConnection (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/client.js:286:13)
at Runner.ensureConnection (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/execution/runner.js:259:46)
at Runner.run (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/execution/runner.js:30:30)
at Raw.Target.then (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/builder-interface-augmenter.js:24:43)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Closing connection with database
Running query
Error: Unable to acquire a connection
at Client_MSSQL.acquireConnection (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/client.js:286:13)
at Runner.ensureConnection (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/execution/runner.js:259:46)
at Runner.run (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/execution/runner.js:30:30)
at Raw.Target.then (/Users/davidbouckaert/Documents/Qite/TIDE_repo/node_modules/knex/lib/builder-interface-augmenter.js:24:43)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Closing connection with database```
It looks like the connection is made (see console log: Running query).
Any idea what's going on?
You should use code like below, it works for me.
const knex = require('knex')({
client: 'mssql',
connection: {
// no tcp:
server: 'j***2sqlserver.database.windows.net',
user: 'j***2',
password: 'J****0',
database: 'yourdbname',
port: 1433,
options: { requestTimeout: 350000, encrypt: true },
},
pool: {
min: 0,
max: 15,
},
});
My Test Result.
You should not call knex.destroy() if you are going to make more queries to the DB.
Move that knex.destroy() call to somewhere just before application is going to exit.

Why won't Sequelize/Tedious connect to a localhost database?

I've been building a NodeJS/React app which connects to an MS SQL Server database. It was working fine, I uploaded it to the Windows hosting and it was working fine connecting to the dev database on a third party hosting company using this config file.
const Sequelize = require('sequelize');
const config = {
user: "myusername",
password: "mypassword",
server: "database_server",
database: "mydatabase",
options: {
enableArithAbort: true
},
};
const seqInstance = new Sequelize(
//
config.database,
config.user,
config.password,
{
dialect: "mssql",
host: config.server,
dialectOptions: {
encrypt: true,
options: {
validateBulkLoadParameters: true
}
},
}
);
module.exports = { seqInstance };
But when I try to connect to the production database which is on the same server, localhost, using this change to the config -
const config = {
user: "mynewusername",
password: "mynewpassword",
server: "localhost",
database: "myproductiondatabase",
options: {
enableArithAbort: true
},
};
it refuses to connect and throws this error.
There are other app on the server connecting to that localhost sql server databases. Why is this small change not working?

How to connect AWS elasticache redis from Node.js application?

How to connect AWS elasticache redis from Node.js application ?
You're connecting to Redis. The fact that it's a managed AWS service is not really that important in this respect.
So, use a Node.js package that implements a Redis client interface, for example:
redis
node-redis
You can use the package ioredis
and stablish a connection like this
const Redis = require('ioredis')
const redis = new Redis({
port: 6379,
host: 'your-redis-host',
connectTimeout: 10000 // optional
});
You can try connecting using ioredis.
var Redis = require('ioredis');
var config = require("./config.json");
const redis = new Redis({
host: config.host,
port: config.port,
password: config.password, // If you have any.
tls: {}, // Add this empty tls field.
});
redis.on('connect', () => {
console.log('Redis client is initiating a connection to the server.');
});
redis.on('ready', () => {
console.log('Redis client successfully initiated connection to the server.');
});
redis.on('reconnecting', () => {
console.log('Redis client is trying to reconnect to the server...');
});
redis.on('error', (err) => console.log('Redis Client Error', err));
//check the functioning
redis.set("framework", "AngularJS", function(err, reply) {
console.log("redis.set ", reply);
});
redis.get("framework", function(err, reply) {
console.log("redis.get ", reply);
});

Connect to mysql on correct port JS

hey using a javascript app im making as a backend server for my website i keep getting this as an error when trying to connect to my mysql server.
ConnectionError: Failed to connect to win2k16-mcdmz:1433 - Could not connect (sequence)
and this is my script to connect to the server. is there any ideas on why it is set to 1433?
private initializeServer() {
const config = {
user: 'MCAdmin',
password: '*******',
server: 'win2k16-mcdmz',
port: 3306,
database: 'ValorantLFG',
encrypt: true
};
mysql.connect(config, (err) => {
if (err) { console.log(err); }
this.init.lfgRequestsTimeout();
//this.init.noticesTimeout();
});
}

Categories