Lzm

nodejs结合mysql初始化配置和使用示例

2025-06-22 17:04:21

Node.js 常用的 MySQL 驱动有两个:

mysql2(推荐):性能更好,支持 Promise 和预处理语句。
mysql(旧版):基础功能,回调风格。

创建连接池

javascript 复制代码
import mysql from "mysql2/promise"; // 使用 Promise 版本

// 创建连接池
const pool = mysql.createPool({
    host: "localhost",
    user: "root",
    password: "your-pass",
    database: "your-database",
    waitForConnections: true, // 允许排队等待
    connectionLimit: 10, // 连接池大小
    queueLimit: 0, // 当 waitForConnections=true 时,等待队列的最大长度,0:不限制队列长度
});

export default pool;

增删改查和事务的示例写法

javascript 复制代码
// 查询数据(SELECT)
const [rows] = await pool.query(
    "SELECT * FROM users WHERE id = ?",
    [id] // id 会被自动转义
);
console.log(rows[0]);

// 插入数据(INSERT)
const [result] = await pool.query(
    "INSERT INTO users (name, email) VALUES (?, ?)",
    [name, email] // 自动防注入
);
console.log(result.insertId); // 返回新插入的 ID

// 更新数据(UPDATE)
const [result] = await pool.query(
    "UPDATE users SET email = ? WHERE id = ?",
    [newEmail, id] // 参数化保证安全
);
console.log(result.affectedRows); // 返回受影响的行数

// 删除数据(DELETE)
const [result] = await pool.query(
    "DELETE FROM users WHERE id = ?",
    [id] // 安全删除
);
console.log(result.affectedRows);

// 事务处理(Transactions)
async function transferMoney(senderId, receiverId, amount) {
    const conn = await pool.getConnection();
    try {
        await conn.beginTransaction();

        // 扣款
        await conn.query("UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, senderId]);

        // 存款
        await conn.query("UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, receiverId]);

        await conn.commit();
        return true;
    } catch (err) {
        await conn.rollback();
        throw err;
    } finally {
        conn.release(); // 释放连接
    }
}
// 使用
await transferMoney(1, 2, 100); // 从用户1转账100给用户2
End