Raw SQL

Last updated


This page explains how to run hand-written SQL with read(), write(), and query().

Three Entry Points


MethodPoolWhen the pool is missing
read<T>(sql, params?)Read poolThrows Read pool connection is not available.
write<T>(sql, params?)Write poolThrows Write pool connection is not available.
query<T>(sql, params?, target?)target; when omitted, the target of the most recent table() callThrows read connection is not available. or write connection is not available.

All three run through query(), so they get the same slow query log and automatic connection release.

Parameter Binding


Pass values through ? placeholders and let mysql2 escape them:
  1. import MySQLPool from "@pardnchiu/mysql-pool";
  2. import type { ResultSetHeader, RowDataPacket } from "mysql2/promise";
  3. try {
  4. const rows = await MySQLPool.read<RowDataPacket[]>(
  5. "SELECT id, name FROM users WHERE deleted_at IS NULL AND (role = ? OR role = ?)",
  6. ["admin", "editor"]
  7. );
  8. const header = await MySQLPool.write<ResultSetHeader>(
  9. "UPDATE users SET last_login = NOW() WHERE id = ?",
  10. [rows[0].id]
  11. );
  12. console.log(header.affectedRows);
  13. } catch (err) {
  14. console.error("raw query failed:", err);
  15. }

The generic T is only a type assertion. The return value is the first element of mysql2's query() result: an array of rows for SELECT and a ResultSetHeader for INSERT/UPDATE/DELETE.

中文