# 生命週期與關閉

本頁說明連線池從 `init()` 建立、到 `close()` 關閉的完整生命週期。

## `init()`

1. 依優先序解析讀寫設定（見 [設定](/zh/configuration)）
2. `database` 非空的一側以 `createPool()` 建立連線池
3. 各取一條連線後立即釋放，確認帳密與網路可用
4. 任一步驟失敗時 `console.error("MySQL initialization failed:", err)` 並拋出原錯誤

## `close()`

依序 `end()` 讀取池與寫入池，並把參考設為 `null`（`src/MySQLPool.ts:99-115`）。之後的查詢會拋出 `... connection is not available.`，可再次呼叫 `init()` 重新建立。關閉失敗時輸出 `Failed to close MySQL connections:` 並拋出原錯誤。

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

await MySQLPool.init();
try {
  await MySQLPool.table("jobs", "write").where("status", "pending").get();
} finally {
  await MySQLPool.close();
}
```

## 狀態

```mermaid
stateDiagram-v2
    [*] --> 未初始化
    未初始化 --> 就緒: init() 成功
    未初始化 --> 未初始化: init() 失敗並拋出
    就緒 --> 已關閉: close()
    已關閉 --> 就緒: init()
```

## 相關頁面

- [讀寫連線池](/zh/read-write-pools)
- [設定](/zh/configuration)
