In node js,I have created a pool for database connectivity
var pool = mysql.createPool( // use a pool for multiple connections
{
connectionLimit : 4,
waitForConnections : true,
queueLimit : 0,
host : hostName,
user : userName,
password : passName,
database : databaseName
});
After making four connections the code works fine.
But after five connection requests are queued in pool for connection and then I make a connection request as
pool.getConnection(funtion(err){
if(err)
console.log('[error] with connection'+err);
});
Then Error occurs --->
[error] with connection Error: ER_USER_LIMIT_REACHED: User 'b1312146aa0cc6' has
exceeded the 'max_user_connections' resource (current value: 4)
try this:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 4,
waitForConnections: true,
queueLimit: 0,
host: hostName,
user: userName,
password: passName,
database: databaseName
});
var sql = 'select * from bag where id = ?';
var args = [1]
pool.query(sql, args, function(err, result) {
console.log('result:', result);
})
pool.query(sql, args, function(err, result) {
console.log('result:', result);
})
pool.query(sql, args, function(err, result) {
console.log('result:', result);
})
pool.query(sql, args, function(err, result) {
console.log('result:', result);
})
pool.query(sql, args, function(err, result) {
console.log('result:', result);
})
// ...
Related
I'm new to Node and learning how to query data from MySQL.
I'm trying to use a pool connection with node.js and mysql but after some queries I get this error message
Error: ER_CON_COUNT_ERROR: Too many connections
{
code: 'ER_CON_COUNT_ERROR',
errno: 1040,
sqlMessage: 'Too many connections',
sqlState: undefined,
fatal: true
}
my code :
const mysql = require('mysql')
class database{
connect(database){
const pool = mysql.createPool({
connectionLimit : 10, //important
host : "localhost",
password: "psw",
user: "root",
database : "database",
multipleStatements: true,
debug : false
});
return pool
}
select(database,data,where,cound){
const link = this
return new Promise(function (resolve, reject) {
const pool = link.connect(database[0])
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
let sql = "select "+data+" from "+link.table+" "+where+" "+cound+";";
connection.query(sql, function (error, results, fields) {
if (error) throw error;
connection.release();
resolve(results)
});
});
})
}
}
I can't solve this problem. thanks for your explain easily
In my Node script I use MySQL and to be able to handle multiple connections I use a connection pool.
Today I forgot to release a connection in the mysql pool. It took me a long time to figure out what the problem was because there was no error shown anywhere.
My code:
const mysql = require('mysql');
const pool = mysql.createPool({
host : 'x',
user : 'x',
password : '#x',
database : 'x',
connectionLimit: 2
});
function executeQuery(){
pool.getConnection((err, connection) => {
if(err) console.log(err);
let query = mysql.format("SELECT * FROM users WHERE id = ?", 1);
connection.query(query, (err, rows) => {
if(err) console.log(err);
console.log(rows);
});
});
}
executeQuery(); // outputs the user as expected
executeQuery(); // outputs the user as expected
executeQuery(); // there is no output in the console, it just looks like nothing happened
My question: How to find out if there are still connections available and if there are no connection available anymore show an error or handle it in a different way?
You forgot to release your connection:
function executeQuery(){
pool.getConnection((err, connection) => {
if(err) console.log(err);
connection.query("SELECT * FROM users WHERE id = ?", [ 1 ], (err, rows) => {
connection.release(); // Give it back or else it gets lost
if(err) console.log(err);
console.log(rows);
});
});
}
There's also no reason to grab the connection like that, you can just use the pool:
function executeQuery() {
pool.query("SELECT * FROM users WHERE id = ?", [ 1 ], (err, connection) => {
if(err) console.log(err);
console.log(rows);
});
}
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;
});
});
I am trying to write a simple AWS Lamda function in nodejs to read and return data from an AWS RDS mySQL database, but the code always only returns:
Response:null
when it is supposed to return the value 'Bbbb', which is the name of emp_id = 2 in my database.
Any help would be really appreciated!
Below is my Lamda code:
var mysql = require('mysql');
var config = require(./config.json)
var pool = mysql.createPool({
host: config.dbhost,
user: config.dbuser,
password: config.dbpassword,
database: config.dbname,
port: 3306
});
exports.handler = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
pool.getConnection(function(err, connection) {
connection.query('SELECT emp_name FROM employee_info WHERE emp_id = 2', function(error, results, fields) {
if (err) callback(error);
callback(null,results[0].emp_name);
connection.release();
});
});
};
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;