NodeJS MySQL - How to know connection is release or not - mysql

I am developing NodeJS + MySQL web API.
I am using mysql npm module.
I want know connection is release or not is there any function or variable.
Like
if(!connection.isRelease() OR !connection.isClose() OR !connection.end()) {
connection.release();
}
Is there any specific function to know connection is release or not?
I am getting error like "connection already release"

You can check if the connection is in the pool to see if it was released. The index in the free connections will be -1 if the connection is not released. Here is an example.
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : ''
});
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
console.log(pool._freeConnections.indexOf(connection)); // -1
connection.release();
console.log(pool._freeConnections.indexOf(connection)); // 0
});
});

Just in case you don't have access to the pool you can also do this:
connection._pool._freeConnections.indexOf(connection)
This will give you the same answer as the accepted answer.

Related

Server NodeJs crashes in idle time and how do I fix it?

My server api is on alwayse alwaysdata.
After x time the server crash.
events.js:183
throw er;
// Unhandled 'error' eventError: Connection lost: The server closed the connection.
at Protocol.end (/home/ec2-user/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/home/ec2-user/node_modules/mysql/lib/Connection.js:97:28)
at Socket.<anonymous> (/home/ec2-user/node_modules/mysql/lib/Connection.js:502:10)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
I'm looking at whether this could not be related to a mysql error. but pre-existing posts do not help me. I think the server mysql cut the connection I do not know why.
here I establish the connection:
let con = mysql.createConnection({
host: "alwaysdata.net",
user: "user",
password: "",
database: "database"
});
try {
con.query(check, (err, customer) => {
if (err){
console.log("%s Error on check query",Date());
throw err;
}
try connection pool:
const mysql = require('mysql');
let pool = mysql.createPool(
{
connectionLimit : 100,
host : '172.17.0.1',
port : 3306,
user : 'test',
password : 'test',
database : 'test',
multipleStatements: true
}
);
...
pool.query(sql, params, function(err, rows) {
...
it works stably on my versions of mysql 5.7 and 8
I believe there are two ways you can handle this.
1) Force MySQL to keep the connection alive (not official, but I believe will do the trick).
2) Handle the mysql server disconnect from the Node's point of
view.
For both there is an excellent example here.
Server disconnects
You may lose the connection to a MySQL server due to network problems,
the server timing you out, the server being restarted, or crashing.
All of these events are considered fatal errors, and will have the
err.code = 'PROTOCOL_CONNECTION_LOST'. See the Error Handling section
for more information.
Re-connecting a connection is done by establishing a new connection.
Once terminated, an existing connection object cannot be re-connected
by design.
With Pool, disconnected connections will be removed from the pool
freeing up space for a new connection to be created on the next
getConnection call.
let connection=null;
function handleDisconnect() {
connection = mysql.createConnection({
host: "alwaysdata.net",
user: "user",
password: "",
database: "database"
}); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function (err) { // The server is either down
if (err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function (err) {
console.log('db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
setInterval(function () {
connection.query('SELECT 1');
}, 5000);
module.exports = connection;
you export the connection object and use this for the other connection queries.
I have called a Query every 5sec to keep the connection alive, i have tried all other approaches and this works like a charm.
Manish's answer worked for me!
I've been struggling with this for the past two days. I had a nodejs server with mysql db running on my localhost and after migrating to heroku with cleardb addon I came across several issues. I had this code in a config file:
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'host',
database: 'database',
user: 'user',
password: 'password', });
module.exports = db;
I changed it to what Manish mentioned to handle the disconnect.

Nodejs (Express) connecting MySQL - Local and Remote connection different?

guys. I am learning how to use Express to connect to remote MySQL. So, I started out doing it on my local machine (a local MySQL server). After I have succeeded on the local environment, I tried changing the the connection to a remote MySQL hosting (at DB4Free). Yes, I have succeeded on the localhost. However, whenever I run a Get/Post to the remote MySQL Server, my console show me the error below. I'll attach the related segment of codes below here. I have been trying it the whole afternoon.
Hope that someone here can enlighten on this matter. Thank you in advance guys :)
This is the error shown in my console
My file for connecting db is as below - ConnectionString.js
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173:3306',
user : '******* ',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};
Portion of my file for the routes and query is this
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var conn = require('../database/ConnectionString');
var result;
//Validate user login
router.get('/login', function(req, res, next) {
conn.getConnection(
function (err, client) {
client.query('SELECT * FROM mt_User', function(err, rows) {
// And done with the connection.
if(err){
console.log('Query Error');
}
res.json(rows);
client.release();
// Don't use the connection here, it has been returned to the pool.
});
});
});
Alright, I have found the issue. It seems that the mysql package in npm requires that the host and port to be defined separately. After tuning it to this code below for my ConnectionString.js file. It finally works.
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173',
port : 3306,
user : '*******',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};

Mysql connection after release in node.js + mysql pool

I cannot understand why could I connect to Mysql after release.
And is there a way to check the status of Mysql ?
Thanks for the help !
var mysqlConfig = {
host : "abcd",
port : "3306",
user : "root",
password : "root",
database : "test"
};
var pool = mysql.createPool(mysqlConfig);
pool.getConnection(function(err, conn) {
// release pool
conn.release();
// After release, Why could I connect to Mysql ????
conn.query('SELECT * FROM user_info WHERE user_id = ?', [id], function(err, rows) {
if (err) {
pushErr();
}
// ...
});
});
Based on the documentation here: https://github.com/felixge/node-mysql it looks like the connection being 'released' doesn't destroy the connection per se, it just signals the pool that it can be used by someone else if needed. If you notice the example, they release as part of the query callback. If you need to actually get rid of the connection, you should use conn.destroy().

Node.js changes in mysql

i have a question regarding about node.js for mysql.
I'm trying to check for changes in the database with node.js and every time it does a change it would do something.
I have the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialpodd',
});
connection.connect();
connection.query('SELECT * FROM personal', function(err, rows, fields) {
if (err) throw err;
console.log('Rows: ', rows[0].email);
});
connection.end();
But I want this code to be called once there is a change in the database. I know I could do a poll method, but it doesn't seem that effective and real-time. What would be a good real-time module that would allow me to do it, or is polling my only option?

What does connection.connect() do in node-mysql?

What does the connection.connect() do in node-mysql library?
My code looks like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ap-cdbr-azure-east-a.cloudapp.net',
user : '<user>',
password : '<password>',
database : '<database>',
});
connection.connect();
Later I run the query.
Even if I remove connection.connect() the code works as is. Some examples have it, some don't. What is the specific purpose for connect() ?
The recommended way to establish a connection is this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
However, a connection can also be implicitly established by invoking a query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) {
// connected! (unless `err` is set)
});
Depending on how you like to handle your errors, either method may be appropriate. Any type of connection error (handshake or network) is considered a fatal error.
Courtesy: https://github.com/felixge/node-mysql