Connecting Node.js applications to a MySQL database server is managed using the modern mysql2/promise driver library, which supports async/await promises, prepared statement caching, and connection pooling.
flowchart TD
A["Node.js HTTP Server Threads"] --> B["MySQL2 Connection Pool"]
B --> C["Active Connection 1"]
B --> D["Active Connection 2"]
B --> E["Active Connection 3"]
C & D & E --> F["MySQL Server RDBMS"]
import mysql from 'mysql2/promise';
// 1. Create a Connection Pool (Recommended Production Strategy)
const dbPool = mysql.createPool({
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '3306'),
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || 'secret',
database: process.env.DB_NAME || 'kodersolution_db',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// 2. Test Connection Health
async function testDatabaseConnection() {
try {
const connection = await dbPool.getConnection();
console.log('Successfully connected to MySQL database server!');
const [rows] = await connection.query('SELECT VERSION() AS version');
console.log('MySQL Server Version:', rows[0].version);
connection.release(); // Return connection to pool
} catch (error) {
console.error('MySQL Connection Error:', error.message);
}
}
testDatabaseConnection();
mysql.createPool() to reuse database socket handles efficiently.connection.release() when manually checking out pool connections to avoid connection exhaustion..env: Never hardcode database credentials in code repositories.What is the advantage of using mysql2/promise over the legacy mysql driver in Node.js?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.