MySQL Node.js

用 mysql2 在 Node.js 里连接、查询、防注入。

Beginner
Key Pointsmysql2 支持 Promise 与连接池,参数化查询天然防注入。

连接与查询

JavaScript
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: '127.0.0.1', user: 'app', password: process.env.DB_PASS,
  database: 'shop', waitForConnections: true, connectionLimit: 10
});

async function listUsers() {
  const [rows] = await pool.query('SELECT id, username FROM users WHERE age > ?', [25]);
  return rows;
}
Output
[
  { id: 1, username: 'alice' },
  { id: 2, username: 'bob' }
]

事务

JavaScript
const conn = await pool.getConnection();
try {
  await conn.beginTransaction();
  await conn.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
  await conn.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
  await conn.commit();
} catch (e) {
  await conn.rollback();
  throw e;
} finally {
  conn.release();
}
In production use a connection pool, not a new connection per call; read credentials from env vars. ORMs (Sequelize/Prisma/TypeORM) wrap mysql2.

Friends & Partners