2 minutes
如何用 Go 連接資料庫
這篇文章主要是寫下,如何用 Go 的標準庫連接到資料庫,以下會列舉:PostgreSQL、MySQL/MariaDB、SQLite。
三種資料庫的連接法都很接近,所以連接的程式碼可以用一樣的,文章專注於解釋 connection string 的差別以及三種資料庫的差別。
像是 SQLite 和 PostgreSQL/MySQL 主要差別是 PostgreSQL/MySQL 都是伺服器和客戶端,但 SQLite 沒有伺服器,是嵌入資料庫管理系統,執行在同一個程式中,只讀一個檔案。
平時開發專案都推薦用 PostgreSQL,因為它的 SQL 版本最合理,有很多功能、免費
資料庫連接db
Postgres
- 下載
github.com/lib/pq
驅動程式來連接:
-
$ createdb 資料庫名字_dev
-
psql "postgres://postgres:postgres@localhost/gohan_dev?sslmode=disable"
sslmode=disable 為 option(disable encryption) -
\q
離開資料庫後,$ nvim main.go
建立一個 main
“database/sql”:使用它來連接資料庫 _ “github.com/lib/pq”: * 驅動程式,用來連接 PostgresSQL * we use the _ identifier to tell Go that we still want this included even though we will never directly reference the package in our code.
SQLite3
- 下載
github.com/mattn/go-sqlite3
驅動程式來連接:
用 go get 就不用 go mod tidy
MySQL/MariaDB
MySQL 和 MariaDB 基本用同一個引擎:
- 下載
github.com/go-sql-driver/mysql
驅動程式來連接:
267 Words
2024-11-01 00:00