Earlier I am working with the single connection but now I am trying to create a DB Pool in Nodejs using Mysql.
I am following the Single Pattern or Class-Based Pattern to create a query and other operations
Earlier Configuration (Everything working fine)
const connection = mysql.createConnection({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB
});
connection.connect();
connection.query("SET AUTOCOMMIT=false;", (err) => {
if(err){
console.log(err)
console.log("Couldn't set auto commit to false")
}else{
console.log("AutoCommit set to false")
}
});
function query(sql, params, autorollback) {
return new Promise((resolve, reject) => {
//let currentTime = new Date().valueOf();
let query = connection.query(sql, params, (err, resp) => {
if(err && autorollback) {
return resolve(rollback(err));
}
else if (err) {
console.log(err)
return reject(err);
}
//console.log("Time Taken: ", new Date().valueOf() - currentTime, "n", query.sql);
//console.log(resp);
resolve(resp);
});
});
}
Create Pool Configuration (Didn’t get the response from the query)
const connection = mysql.createPool({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB,
connectionLimit: 4,
});
connection.getConnection(function (err, conn) {
conn.query("SET AUTOCOMMIT=false;", (err) => {
if (err) {
console.log(err)
console.log("Couldn't set auto commit to false")
} else {
console.log("AutoCommit set to false")
}
});
});
function query(sql, params, autorollback) {
console.log(sql)
return new Promise((resolve, reject) => {
//let currentTime = new Date().valueOf();
connection.getConnection(function (err, conn) {
if (err) {
console.log(err)
return reject(err);
}
let query = conn.query(sql, params, (err, resp) => {
console.log(sql)
if (err && autorollback) {
return resolve(rollback(err));
}
else if (err) {
console.log(err)
return reject(err);
}
//console.log("Time Taken: ", new Date().valueOf() - currentTime, "n", query.sql);
//console.log(resp);
resolve(resp);
conn.release();
});
})
});
}