~/Using SQLite in Go Applications
Jul 15, 2022
To use SQLite in Go use the go-sqlite3 driver. It implements the database/sql interface.
Install using:
1
|
go get github.com/mattn/go-sqlite3
|
Example code to connect and query:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "file:test.db")
if err != nil {
panic(err)
}
defer db.Close()
_, err = db.Exec("CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY, name TEXT);")
if err != nil {
panic(err)
}
_, err = db.Exec("INSERT INTO foo(name) VALUES(?)", "bar")
if err != nil {
panic(err)
}
rows, err := db.Query("SELECT id, name FROM foo")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
println(id, name)
}
}
|
For simple use, no extra setup is needed. For more on configuring options or using features like WAL, check the go-sqlite3 readme. See complete database/sql usage for advanced queries and transactions.