快速開始

最後更新

本頁從安裝到第一筆查詢,帶你完成 @pardnchiu/mysql-pool 的最小可執行設定。

前置需求

項目 版本
Node.js 20 以上(package.json 的 engines.node)
MySQL 8.0 以上;只有 total() 需要 COUNT(*) OVER() 視窗函式,不用 total() 時 5.7 亦可
mysql2 ^3.14.1,安裝套件時一併安裝

安裝

npm install @pardnchiu/mysql-pool

設定連線

最快的方式是設定環境變數。只設定一側時,另一側不會建立連線池,詳見 讀寫連線池。

export DB_READ_HOST=127.0.0.1
export DB_READ_USER=reader
export DB_READ_PASSWORD=secret
export DB_READ_DATABASE=app

export DB_WRITE_HOST=127.0.0.1
export DB_WRITE_USER=writer
export DB_WRITE_PASSWORD=secret
export DB_WRITE_DATABASE=app

也可以直接把設定物件傳給 init(),完整欄位見 設定。

第一筆查詢

import MySQLPool from "@pardnchiu/mysql-pool";

async function main() {
  try {
    // 建立讀寫連線池,並各取一條連線確認可用
    await MySQLPool.init();

    // 預設走讀取池
    const users = await MySQLPool
      .table("users")
      .select("id", "name")
      .where("status", "active")
      .limit(10)
      .get();

    console.log(users);
  } catch (err) {
    console.error("query failed:", err);
  } finally {
    await MySQLPool.close();
  }
}

main();

init() 連不上資料庫時會先以 console.error 輸出 MySQL initialization failed: 再拋出原始錯誤(src/MySQLPool.ts:93)。

第一筆寫入

const id = await MySQLPool
  .table("users")
  .insert({ name: "John Doe", email: "john@example.com" });

await MySQLPool
  .table("users")
  .where("id", id)
  .update({ updated_at: "NOW()" });

insert()、update()、upsert() 一律走寫入池,不受 table() 第二個參數影響。

下一步

EN