哈囉探險家們,歡迎來到鐵人賽 Day 9!
工具(Go)與交通工具(Echo)都到位了,但遊戲要存檔、網頁要記住使用者資料,還缺一個「資料收納箱」——資料庫(Database)。今天主角有兩位:PostgreSQL(穩又強的資料庫)+ pgxpool(Go 和資料庫的溝通管家)。一起把效能與穩定度拉滿!🚀
想像衣櫃:T 恤、褲子、襪子分門別類,要找衣服一秒到位。
資料庫也一樣:把註冊帳號、文章內容、上傳照片整理好,程式想拿什麼,像超快圖書館管理員一樣「嗶一下」就找到。
程式要跟資料庫說話,會先建立一條「通話線路」=連線(Connection)。
一直重撥很耗時,所以我們準備一整桶——連線池(Connection Pool)!
先安裝 Docker(到官網下載)。接著在終端機執行:
docker run --name my-postgres \
-e POSTGRES_PASSWORD=mysecretpassword \
-p 5432:5432 \
-d postgres
--name my-postgres
:幫容器取名字-e POSTGRES_PASSWORD=...
:設定資料庫密碼-p 5432:5432
:把容器的 5432 埠對外開啟(很重要!你的 Go 程式才能連到 localhost:5432)-d postgres
:用官方映像,背景執行小叮嚀:如果想下次重開機還在,記得用 volume 存資料;這章先專注連成功就好。📝
go get github.com/jackc/pgx/v4
新建 main.go
,貼上:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v4/pgxpool"
)
func main() {
// 從環境變數讀取連線字串(較安全)
// 格式:"postgresql://使用者:密碼@主機:port/資料庫"
connStr := os.Getenv("DATABASE_URL")
if connStr == "" {
// 若沒設定就使用 Docker 預設
connStr = "postgresql://postgres:mysecretpassword@localhost:5432/postgres"
}
// Context:這次任務的「通行證」
ctx := context.Background()
// 建立連線池(吸管桶)
pool, err := pgxpool.Connect(ctx, connStr)
if err != nil {
log.Fatalf("無法連線到資料庫: %v", err)
}
// 離開前把門關好
defer pool.Close()
fmt.Println("成功連線到 PostgreSQL!")
// 試刺:問一下版本,確認通了
var serverVersion string
err = pool.QueryRow(ctx, "select version()").Scan(&serverVersion)
if err != nil {
log.Fatalf("查詢失敗: %v", err)
}
fmt.Printf("資料庫版本: %s\n", serverVersion)
}
DATABASE_URL
放密碼與主機資訊在環境變數更安全 🔐pgxpool.Connect
建好可重複使用的連線池,少走冤枉路 ⚡defer pool.Close()
禮貌收尾,釋放資源 🧹QueryRow("select version()")
成功拿到版本=你打通任督二脈 ✅connection refused
:多半是忘了 -p 5432:5432
,或容器尚未啟動POSTGRES_PASSWORD
是否一致localhost
、埠號、資料庫名稱拼對沒?DATABASE_URL
,別寫死在程式碼!你已經把資料庫連起來了,接下來就能開始「尋寶」:新增、查詢、更新、刪除(CRUD)✨
下一篇,我們把寶箱打開,把資料存進去、撈出來。準備升級啦!🗺️🏆
macOS / Linux(暫時在當前 shell):
export DATABASE_URL="postgresql://postgres:mysecretpassword@localhost:5432/postgres"
go run main.go
Windows PowerShell:
$env:DATABASE_URL="postgresql://postgres:mysecretpassword@localhost:5432/postgres"
go run .\main.go