Node JS App resulting in Too Many Connections on MySQL - mysql

This is how my code looks like:
var con = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
con.query('INSERT INTO tbasic SET ?', data, (err, ret) => {
if(err) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:err
});
}
else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
});
Whenever this application runs, after a while I get Too many connections error on the DB.
I know about the possible duplication issue but I have tried almost all solutions I found so far. None of them seems to work. What am I missing here?

Try using the long-handed way of pooling connections
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
pool.getConnection(function(err, connection) {
if (err) throw err; // No connection
connection.query('INSERT INTO tbasic SET ?', function(error, ret) {
if(error) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:error
});
} else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
// Release current connection
connection.release();
// Handle error after connection released
if (error) throw error;
});
});

Related

How to pass multiple parameters for promise function in Nodejs connected with MYSQL server?

let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'priyanka',
password: '1234',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
// promise function
query = `select device from user_table limit 34`;
sql = function(device){
return new Promise(function(resolve,reject)
{
connection.query(query, (error, results) => {
if (error) {
reject( console.error(error.message));
}
resolve(console.log(results));
});
})
}
sql('device').then(function(rows) {
}).catch((err) => setImmediate(() => { throw err; }));
connection.end();
sql('device') -> inside sql call , can i only place comma separated field values to get rows from user_table or is there any other way to pass multiple columns ?

How to make a function to query MySQL in NodeJS?

I made this:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
console.log(query('SELECT * FROM `users`'))
and I got back
Promise { <pending> }
How do I get back my results from querying the database, just like PHP can do?
In PHP I never had to do such a thing like async/await and promises...
I also tried using mysql:
const mysql = require('mysql')
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
function query(query) {
db.query(query, (err, result) => {
if (err) throw err
return result
})
}
console.log(query('SELECT * FROM `users`'))
but I got an undefined result
try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
// function definition
function runQuery (con, sqlQuery) {
return new Promise((resolve, reject) => {
console.log("START");
if(con){
con.connect(function (err) {
if (err) throw err;
});
if (sqlQuery) {
con.query(sqlQuery, function (error, result, fields) {
connection.end(); // end connection
if (error) {
throw error;
} else {
return resolve(result);
}
});
} else {
connection.end(); // end connection
// code: handle the case
}
} else {
// code: handle the case
}
});
}
var sqlQuery = 'SELECT * FROM tableName';
// function call and pass the connection and sql query you want to execute
var p = runQuery(con, sqlQuery);
p.then((data)=>{ // promise and callback function
console.log('data :', data); // result
console.log("END");
});
I am not very familiar with MySQL and the libraries that you are using.
However, the Promise { <pending> } response that you are getting is because you didn't await your query execution.
Since the function is marked as async and is also performing an async action, it returns a Promise that needs to be awaited to be resolved.
The code below should work:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
(async () => {
const queryResult = await query('SELECT * FROM `users`');
console.log(queryResult);
} )();
To understand how async-await works, consider the code below:
console.log('I will get printed first');
const asyncFunction = async () => {
await setTimeout(()=> {}, 1000)
console.log('I will get printed third');
return 'hello'
}
(async () => {
const result = await asyncFunction();
console.log(`I will get printed last with result: ${result}`);
})();
console.log('I will get printed second');
The console.log statement I will get printed last with result will wait for the asyncFunction to complete execution before getting executed.
Try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Make synchronous MySQL queries in NodeJS

I have been doing google searches for 5 days, I hope to find the solution ... I know that it does not work because it is asynchronous, but I need the program (it is a Discord bot) to respond with a data that I get from a DB. I have tried Promises and callbacks, but I do not know if it is because I am a novice with asynchronous, that nothing works for me.
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
function leerPromesa() {
var promise = new Promise(function (resolve, reject) {
con.query('SELECT * from ranking;', function (err, rows, fields) {
if (err) {
reject(err);
return
}
resolve(rows);
rows.forEach(element => console.log(element));
})
});
return promise;
};
var promesa = leerPromesa();
promesa.then(
function (rows) {
rows.forEach(element => msg.reply(element));
},
function (err) {
msg.reply(err);
}
);
con.end();
What the bot does is respond with blank text.
First, you're not really connecting to database.
If you refer to docs https://github.com/mysqljs/mysql:
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
// then connect method
connection.connect();
So your code will never work..
Second, you are closing connection before any query execution:
con.end();
Correct is to close connection after leerPromesa function execution.
Finally, code could look something like this:
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
con.connect();
function leerPromesa() {
return new Promise(function(resolve, reject) {
con.query("SELECT * from ranking;", function(err, rows, fields) {
if (err) {
return reject(err);
}
return resolve(rows);
});
});
}
leerPromesa()
.then(
function(rows) {
rows.forEach(element => msg.reply(element));
},
function(err) {
msg.reply(err);
}
)
.finally(function() {
con.end();
});
I used finally method on Promise to close connection in every situation https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

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;

Terminating a callback in nodejs

I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
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.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});