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
Related
My question is similar to this post but the solution didnt work for me probably because im using a different type of mysql connection (pool). This is my code:
let config= {
host: '***',
user: 'admin',
password: '***',
port: '3306',
database: '***',
multipleStatements: true
};
const con = mysql.createPool(config);
select();
function select(){
return new Promise((resolve, reject) => {
con.getConnection(function (err, connection) {
if (err) throw err;
else
console.log("Connected!");
let sql = "SELECT * FROM bidPrice WHERE idExchangePlatform = 2;";
connection.query(sql, function (err, results, fields) {
connection.release();
connection.destroy();
if (err) throw err;
console.log(results)
resolve(results);
});
});
});
}
I also important to mention that im running this function using the following command
node --max-old-space-size=31744 index.js # Increase to 31 GB
This is because im working with millions of records from the database query If i run this with regular node command i would be getting Javascript heap out of memory
When i tried integrating the solution i mentioned earlier to my code i just get a "killed" log after a while and then the process stops, should i handle server disconnect in a different way when using mysql.pool?
I have an API server which runs different API calls to a mysql database: this is the file which entirely handles the connections and the queries:
const mysql = require('mysql')
const pool = mysql.createPool({
host: sqlhost,
port: sqlport,
user: sqluser,
password: sqlpsw,
database: sqldb,
charset: 'utf8mb4',
connectionLimit: 10
})
module.exports = {
get: function (sqlQuery, type) {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) reject(new Error(505))
else {
connection.query(sqlQuery, function (err, results) {
connection.release()
if (err !== null) reject(new Error(503))
else resolve(results)
})
}
})
})
}
}
After some time I get the Error: ER_CON_COUNT_ERROR: Too many connections.
I know i may have used pool.query instead of the flow pool.getConnection --> connection.query --> connection.release but the result is (I guess) the same.
I have no idea what is causing the "connections leak". Any idea? Thanks
I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
const express = require('express');
const mysql = require('mysql');
//Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'ca1903'
});
//Connect
db.connect(() => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
const app = express();
//create DB
app.get('/createdb', () => {
let sql = 'CREATE DATABASE ca1903';
db.query(sql, (err, result) => {
if(err){
console.log(err);
}
console.log(result);
res.send('database created....');
});
});
You were missing err parameter in the db.connect call. It should be in the below way.
// Connect
db.connect((err) => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
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;
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);
})
// ...