首先需要创建连接池实例:
const mysql = require('mysql2/promise'); // 使用Promise版本
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test',
waitForConnections: true,
connectionLimit: 10, // 最大连接数
queueLimit: 0 // 无限制的排队请求
});
pool.query(sqlString, [values])
[rows, fields]
const [rows] = await pool.query('SELECT * FROM users WHERE age > ?', [18]);
pool.execute(sqlString, [values])
query()
更高效(特别是重复查询)[rows, fields]
const [rows] = await pool.execute('SELECT * FROM products WHERE price > ?', [100]);
pool.getConnection()
const connection = await pool.getConnection();
try {
// 使用connection执行查询
} finally {
connection.release(); // 必须释放
}
通过getConnection()
获取的连接对象有以下方法:
connection.query()
pool.query()
,但在特定连接上执行connection.execute()
pool.execute()
,但在特定连接上执行connection.beginTransaction()
await connection.beginTransaction();
connection.commit()
await connection.commit();
connection.rollback()
await connection.rollback();
connection.release()
pool.end()
await pool.end(); // 关闭所有连接
pool.escape(value)
const name = pool.escape(userInput); // 防止SQL注入
pool.escapeId(identifier)
const tableName = pool.escapeId('user table');
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
// 执行多个操作
await connection.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
await connection.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
await connection.commit();
} catch (err) {
await connection.rollback();
throw err;
} finally {
connection.release();
}
连接池可以监听以下事件:
'acquire'
pool.on('acquire', (connection) => {
console.log('Connection %d acquired', connection.threadId);
});
'release'
pool.on('release', (connection) => {
console.log('Connection %d released', connection.threadId);
});
'enqueue'
pool.on('enqueue', () => {
console.log('Waiting for available connection slot');
});
execute()
比query()
更高效end()
关闭这些方法涵盖了MySQL连接池的绝大多数使用场景,合理使用可以构建高效可靠的数据库应用。