nodejs mysql connection pool
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase'
});
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.');
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.');
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.');
}
}
if (connection) {
connection.release();
}
return;
});
module.exports = pool;
Explanation:
Require the 'mysql' module: Import the 'mysql' package to enable interaction with MySQL databases.
Create a Connection Pool: The
createPool()
method is used to create a pool of connections to the MySQL database. Parameters such asconnectionLimit
,host
,user
,password
, anddatabase
are provided to configure the pool settings and connect to the specific database.Handle Pool Connections:
pool.getConnection()
is used to retrieve a connection from the pool. It takes a callback function with parameterserr
(error) andconnection
. Inside the callback, error handling is performed. If there's an error, different error codes such as 'PROTOCOL_CONNECTION_LOST', 'ER_CON_COUNT_ERROR', or 'ECONNREFUSED' are checked and respective error messages are logged. If there's a connection, it's released back to the pool to be reused.Export the Pool: The
module.exports
statement is used to export the created pool, making it available for use in other files/modules within the Node.js application.