Connection pooling helps manage database connections efficiently. What is the primary advantage of using connection pooling?
Think about what happens when you open and close connections repeatedly.
Connection pooling keeps a set of open connections ready to use, so the app doesn't need to open a new connection every time. This saves time and resources.
Consider a connection pool with a limited number of connections. What happens if all connections are currently in use and a new query requests a connection?
Think about how a waiting line works when resources are limited.
When all connections are busy, new requests wait in a queue until a connection becomes free. This prevents overload and manages resources efficiently.
Choose the code that properly creates a connection pool with a maximum of 5 connections.
Check the exact option name for limiting connections in the pool.
The 'mysql2' package uses 'connectionLimit' to set the max number of connections. Option A uses correct syntax and option name.
Consider this code snippet:
const mysql = require('mysql2');
const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test' });
pool.query('SELECT 1', (err, results) => {
if (err) throw err;
console.log(results);
});
pool.end();
pool.query('SELECT 2', (err, results) => {
if (err) throw err;
console.log(results);
});Why does the second query cause an error?
Think about what pool.end() does to the connection pool.
Calling pool.end() closes all connections and disables the pool. Any queries after that cause errors because no connections are available.
Given the following code, what will be printed to the console?
import mysql from 'mysql2/promise';
async function testPool() {
const pool = mysql.createPool({ host: 'localhost', user: 'root', database: 'test', connectionLimit: 2 });
const conn1 = await pool.getConnection();
const conn2 = await pool.getConnection();
let errorCaught = false;
try {
const conn3 = await pool.getConnection({ timeout: 100 });
} catch (e) {
errorCaught = true;
console.log('Timeout error caught');
}
conn1.release();
conn2.release();
await pool.end();
console.log('Error caught:', errorCaught);
}
testPool();Consider the pool size and what happens when requesting more connections than the limit with a timeout.
The pool has 2 connections max. Getting two connections uses them all. The third getConnection call times out and throws an error, caught and logged. Then 'Error caught: true' is printed.