> For the complete documentation index, see [llms.txt](https://willh.gitbook.io/build-web-application-with-golang-zhtw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://willh.gitbook.io/build-web-application-with-golang-zhtw/05.0/05.3.md).

# 使用 SQLite 資料庫

SQLite 是一個開源的嵌入式關聯式資料庫，實現自套件容、零配置、支援事務的 SQL 資料庫引擎。其特點是高度便攜、使用方便、結構緊湊、高效、可靠。 與其他資料庫管理系統不同，SQLite 的安裝和執行非常簡單，在大多數情況下，只要確保 SQLite 的二進位制檔案存在即可開始建立、連線和使用資料庫。如果您正在尋找一個嵌入式資料庫專案或解決方案，SQLite 是絕對值得考慮。SQLite 可以說是開源的 Access。

## 驅動

Go 支援 sqlite 的驅動也比較多，但是好多都是不支援 database/sql 介面的

* <https://github.com/mattn/go-sqlite3> 支援 database/sql 介面，基於 cgo(關於 cgo 的知識請參看官方文件或者本書後面的章節)寫的
* <https://github.com/feyeleanor/gosqlite3> 不支援 database/sql 介面，基於 cgo 寫的
* <https://github.com/phf/go-sqlite3>  不支援 database/sql 介面，基於 cgo 寫的

目前支援 database/sql 的 SQLite 資料庫驅動只有第一個，我目前也是採用它來開發專案的。採用標準介面有利於以後出現更好的驅動的時候做遷移。

## 範例程式碼

範例的資料庫表結構如下所示，相應的建表 SQL：

```sql
CREATE TABLE `userinfo` (
    `uid` INTEGER PRIMARY KEY AUTOINCREMENT,
    `username` VARCHAR(64) NULL,
    `department` VARCHAR(64) NULL,
    `created` DATE NULL
);

CREATE TABLE `userdetail` (
    `uid` INT(10) NULL,
    `intro` TEXT NULL,
    `profile` TEXT NULL,
    PRIMARY KEY (`uid`)
);
```

看下面 Go 程式是如何操作資料庫表資料 : 增刪改查

```go
package main

import (
    "database/sql"
    "fmt"
    "time"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    db, err := sql.Open("sqlite3", "./foo.db")
    checkErr(err)

    //插入資料
    stmt, err := db.Prepare("INSERT INTO userinfo(username, department, created) values(?,?,?)")
    checkErr(err)

    res, err := stmt.Exec("astaxie", "研發部門", "2012-12-09")
    checkErr(err)

    id, err := res.LastInsertId()
    checkErr(err)

    fmt.Println(id)
    //更新資料
    stmt, err = db.Prepare("update userinfo set username=? where uid=?")
    checkErr(err)

    res, err = stmt.Exec("astaxieupdate", id)
    checkErr(err)

    affect, err := res.RowsAffected()
    checkErr(err)

    fmt.Println(affect)

    //查詢資料
    rows, err := db.Query("SELECT * FROM userinfo")
    checkErr(err)

    for rows.Next() {
        var uid int
        var username string
        var department string
        var created time.Time
        err = rows.Scan(&uid, &username, &department, &created)
        checkErr(err)
        fmt.Println(uid)
        fmt.Println(username)
        fmt.Println(department)
        fmt.Println(created)
    }

    //刪除資料
    stmt, err = db.Prepare("delete from userinfo where uid=?")
    checkErr(err)

    res, err = stmt.Exec(id)
    checkErr(err)

    affect, err = res.RowsAffected()
    checkErr(err)

    fmt.Println(affect)

    db.Close()

}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}
```

我們可以看到上面的程式碼和 MySQL 例子裡面的程式碼幾乎是一模一樣的，唯一改變的就是匯入的驅動改變了，然後呼叫`sql.Open`是採用了 SQLite 的方式開啟。

> sqlite 管理工具：<http://sqliteadmin.orbmu2k.de/>
>
> 可以方便的建立資料庫管理。

## links

* [目錄](https://github.com/doggy8088/build-web-application-with-golang-zhtw/tree/4cbbaa31bdfc3678915eb91f23db2f1bad554a20/preface.md)
* 上一節: [使用 MySQL 資料庫](/build-web-application-with-golang-zhtw/05.0/05.2.md)
* 下一節: [使用 PostgreSQL 資料庫](/build-web-application-with-golang-zhtw/05.0/05.4.md)
