Performance: MySQL connection with mysql2
This affects the initial page or API response load time by how quickly the database connection is established and queries are executed.
import mysql from 'mysql2/promise'; const pool = mysql.createPool({host: 'localhost', user: 'root', database: 'test', waitForConnections: true, connectionLimit: 10}); async function getUsers() { const [rows] = await pool.query('SELECT * FROM users'); return rows; }
const mysql = require('mysql2'); const connection = mysql.createConnection({host: 'localhost', user: 'root', database: 'test'}); connection.query('SELECT * FROM users', (err, results) => { if (err) throw err; console.log(results); }); connection.end();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single connection per query | N/A | N/A | N/A | [X] Bad |
| Connection pool with async queries | N/A | N/A | N/A | [OK] Good |
mysql2 package in Node.js?mysql2 package is designed to help Node.js applications connect to and communicate with MySQL databases.mysql2.mysql2 in Node.js?createConnection with an object containing host, user, password, and database.createConnection with all required fields. Options A, B, and D use incorrect method names or missing parameters.const mysql = require('mysql2');
const connection = mysql.createConnection({host: 'localhost', user: 'root', password: 'pass', database: 'test'});
connection.connect(err => {
if (err) {
console.log('Connection failed');
} else {
console.log('Connected successfully');
}
});err is null, so the else block runs.const mysql = require('mysql2');
const connection = mysql.createConnection({host: 'localhost', user: 'root', password: 'pass'});
connection.connect(err => {
if (err) throw err;
console.log('Connected!');
});
connection.end();connection.end() is called immediately after connect(), which may close connection before it is established or query runs.connect first, ensuring connection is ready before running the query.conn.end() inside the query callback, so connection closes only after query finishes.conn.end() immediately after query, which may close connection too soon. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.end();
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
}); closes connection before query. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass'});
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
}); misses database in config.Pass the test and this pattern moves unknown