nodejs to mysql connection error - mysql

I'm getting error :
error:Error: Handshake inactivity timeout

I connected mysql to node by like this.
Install mysql
npm install mysql
var mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
port: '8888', /* port on which phpmyadmin run */
password: 'root',
database: 'dbname',
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock' //for mac and linux
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});

You can use node-mysql, It very easy to use. I have used once, Here is the example :-
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();

Use Connection Pool:
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'example.org',
user : 'bob',
password : 'secret'
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});

Related

Release Connection When Query Is Complete

I have a question, Before I change my code, I got error [error: connection lost: the server closed the connection.], possibly because its idle for sometime.
This is my old code.
const dbConn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
dbConn.connect(function(err) {
if(err) throw err;
console.log("Database Connected!");
})
module.exports = dbConn;
After searching for a while, most of it recommend using createPool intead of createConnection, so I change my code to this
const dbConn = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
module.exports = dbConn;
Then my question is, do I have to release the connection everytime we complete a query? This is how I do query.
dbConn.query("SELECT * FROM spesialisasi s ORDER BY s.nama_spesialisasi ASC ",
function(err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
}
)
From my knowledge, pool.query() will automatically release the connection when the query completes. Here's the section on connection pooling from the MySQL NPM docs

How to connect mysql with nodejs

I want to connect my database with nodejs but it's not connecting and giving an Error: connect ETIMEDOUT.
My code is...
var con = mysql.createConnection({
host: hostname,
user: user,
password: pass,
database: database_name,
});
con.connect(function (error) {
if (error) console.log("Not Connected: " + error);
else console.log("connected");
});
const mysql = require('mysql');
const dbPool = mysql.createPool({
connectionLimit : 10,
port : 'port of your Db',
host : 'host of your Db,
user : 'user of your Db,
password : 'password of your Db,
database : 'database name,
dateStrings : true,
debug : false
});

Error while performing Query. node-mysql.js:15

I tried simple mysql connection in nodejs but got this error, checked with the sql connection....server is up and running....please help!
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '****',
database : 'todo'
});
connection.connect();
connection.query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
Output:
Debugger listening on ws://127.0.0.1:48226/9809e9bf-990f-4d1e-9d98-420af454907f
Error while performing Query.

NodeJS: How to use Connection Pooling with MySQL correctly? How useful it is?

I'm using connection pooling in NodeJS with MySQL. There are several connections remain in processlist in Sleep state, which results too many connection in the end even if site does not have heavy traffic.
Here is sample code as I'm using it:
var pool = mysql.createPool({
host: '127.0.0.1',
user: '***',
password: '***',
database: '****'
});
pool.getConnection(function (err, connection) {
connection.query("SELECT * from test", function (error, data) {
connection.release();
if (error) {
console.log(error);
} else {
// perform further process
}
});
});
Is connection not released at proper location? Suggest if there could be any improvement in code above.
That is what pool does, you can add connection limit...
var pool = mysql.createPool({
connectionLimit : 10,
host: '127.0.0.1',
user: '***',
password: '***',
database: '****'
});

How do I create a MySQL connection pool while working with NodeJS and Express?

I am able to create a MySQL connection like this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
But I would rather like to initiate a pool and use it across my project.
Just to help some one in future, this worked for me:
I created a mysql connector file containing the pool:
// Load module
var mysql = require('mysql');
// Initialize pool
var pool = mysql.createPool({
connectionLimit : 10,
host : '127.0.0.1',
user : 'root',
password : 'root',
database : 'db_name',
debug : false
});
module.exports = pool;
Later you can simply include the connector in another file lets call it manageDB.js:
var pool = require('./mysqlConnector');
And made a callable method like this:
exports.executeQuery=function(query,callback){
pool.getConnection(function(err,connection){
if (err) {
connection.release();
throw err;
}
connection.query(query,function(err,rows){
connection.release();
if(!err) {
callback(null, {rows: rows});
}
});
connection.on('error', function(err) {
throw err;
return;
});
});
}
You can create a connection file, Let's called dbcon.js
var mysql = require('mysql');
// connect to the db
dbConnectionInfo = {
host: "localhost",
port: "3306",
user: "root",
password: "root",
connectionLimit: 5, //mysql connection pool length
database: "db_name"
};
//For mysql single connection
/* var dbconnection = mysql.createConnection(
dbConnectionInfo
);
dbconnection.connect(function (err) {
if (!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
*/
//create mysql connection pool
var dbconnection = mysql.createPool(
dbConnectionInfo
);
// Attempt to catch disconnects
dbconnection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
module.exports = dbconnection;
Now include this connection to another file
var dbconnection = require('../dbcon');
dbconnection.query(query, params, function (error, results, fields) {
//Do your stuff
});
There is some bugs in Utkarsh Kaushik solution:
if (err), the connection can not be released.
connection.release();
and when it has an err, next statement .query always execute although it gets an error and cause the app crashed.
when the result is null although query success, we need to check if the result is null in this case.
This solution worked well in my case:
exports.getPosts=function(callback){
pool.getConnection(function(err,connection){
if (err) {
callback(true);
return;
}
connection.query(query,function(err,results){
connection.release();
if(!err) {
callback(false, {rows: results});
}
// check null for results here
});
connection.on('error', function(err) {
callback(true);
return;
});
});
};
You do also can access the Mysql in a similar way by firstly importing the package by entering npm install mysql in the terminal and installing it & initialize it.
const {createPool} = require("mysql");
const pool = createPool({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
)};
module.exports = pool;