API 參考
最後更新
本頁列出 MySQLPool 所有公開 static 方法的簽章、回傳值與對應的說明頁。
匯出
import MySQLPool from "@pardnchiu/mysql-pool"; // 預設匯出
import { MySQLPool } from "@pardnchiu/mysql-pool"; // 具名匯出
MySQLPool 的建構子為 private,所有方法皆為 static。建構方法回傳 typeof MySQLPool 以便串接。
生命週期
| 方法 | 簽章 | 說明 |
|---|---|---|
init |
init(config?: Record<string, MySQLConfig>): Promise<void> |
建立並驗證讀寫連線池,見 設定 |
close |
close(): Promise<void> |
關閉兩個連線池,見 生命週期與關閉 |
查詢建構
| 方法 | 簽章 | 說明 |
|---|---|---|
table |
table(tableName: string, target?: "read" | "write"): typeof MySQLPool |
重設狀態、指定資料表與 get() 的連線池,預設 "read" |
select |
select(...fields: string[]): typeof MySQLPool |
指定欄位,見 欄位與條件 |
where |
where(column: string, operator: any, value?: any): typeof MySQLPool |
加入 AND 條件 |
innerJoin |
innerJoin(table: string, first: string, operator: string, second?: string): typeof MySQLPool |
見 資料表關聯 |
leftJoin |
同 innerJoin |
LEFT JOIN |
rightJoin |
同 innerJoin |
RIGHT JOIN |
orderBy |
orderBy(column: string, direction?: "ASC" | "DESC" | "asc" | "desc"): typeof MySQLPool |
見 排序與分頁 |
limit |
limit(num: number): typeof MySQLPool |
LIMIT |
offset |
offset(num: number): typeof MySQLPool |
OFFSET |
total |
total(): typeof MySQLPool |
每列附帶 total 總筆數 |
increase |
increase(target: string, number?: number): typeof MySQLPool |
為 update() 加入遞增,見 新增與更新 |
執行
| 方法 | 簽章 | 連線池 | 回傳 |
|---|---|---|---|
get |
get<T = any>(): Promise<T[]> |
table() 指定 |
資料列陣列 |
insert |
insert(data: Record<string, any>): Promise<number | null> |
寫入 | insertId,為 0 時 null |
update |
update(data?: Record<string, any>): Promise<ResultSetHeader> |
寫入 | mysql2 ResultSetHeader |
upsert |
upsert(data: Record<string, any>, updateData?: Record<string, any> | string): Promise<number | null> |
寫入 | insertId,為 0 時 null;見 Upsert |
query |
query<T = any>(query: string, params?: any[], target?: "read" | "write"): Promise<T> |
target 或最近一次 table() |
mysql2 結果陣列第一個元素 |
read |
read<T = any>(query: string, params?: any[]): Promise<T> |
讀取 | 同 query |
write |
write<T = any>(query: string, params?: any[]): Promise<T> |
寫入 | 同 query;見 原生 SQL |
錯誤訊息
| 訊息 | 來源 |
|---|---|
Table not set, query aborted. |
get() 前未呼叫 table() |
Table not set, insert aborted./update aborted./upsert aborted. |
對應方法前未呼叫 table() |
read connection is not available./write connection is not available. |
query() 找不到目標連線池 |
Read pool connection is not available./Write pool connection is not available. |
read()/write() 找不到連線池 |
其餘錯誤(連線失敗、SQL 語法錯誤)為 mysql2 原始錯誤,原樣拋出。