Go 使用go-sqlite 操作sqlite 数据库 go sqlite3 arm64
1、需要使用到的go-sqlite 的 github地址
https://github.com/mattn/go-sqlite3
2、安装go-sqlite
go get github.com/mattn/go-sqlite3
提示:
Important: because this is a CGO enabled package you are required to set the environment variable CGO_ENABLED=1 and have a gcc compile present within your path.
3、示例代码
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
)
func main() {
os.Remove("./foo.db")
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
sqlStmt := `
create table foo (id integer not null primary key, name text);
delete from foo;
`
_, err = db.Exec(sqlStmt)
if err != nil {
log.Printf("%q: %s\n", err, sqlStmt)
return
}
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
for i := 0; i < 10; i++ {
_, err = stmt.Exec(i, fmt.Sprintf("https://const.net.cn %03d", i))
if err != nil {
log.Fatal(err)
}
}
tx.Commit()
rows, err := db.Query("select id, name from foo")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
stmt, err = db.Prepare("select name from foo where id = ?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
var name string
err = stmt.QueryRow("3").Scan(&name)
if err != nil {
log.Fatal(err)
}
fmt.Println(name)
_, err = db.Exec("delete from foo")
if err != nil {
log.Fatal(err)
}
_, err = db.Exec("insert into foo(id, name) values(1, 'const'), (2, 'net'), (3, 'cn')")
if err != nil {
log.Fatal(err)
}
rows, err = db.Query("select id, name from foo")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}
4、编译运行
CGO_ENABLED=1 GOOS=linux go run .
运行结果:
0 https://const.net.cn 000
1 https://const.net.cn 001
2 https://const.net.cn 002
3 https://const.net.cn 003
4 https://const.net.cn 004
5 https://const.net.cn 005
6 https://const.net.cn 006
7 https://const.net.cn 007
8 https://const.net.cn 008
9 https://const.net.cn 009
https://const.net.cn 003
1 const
2 net
3 cn
5、go sqlite3 arm64/aarch64
env CC=aarch64-linux-gnu-gcc CXX=aarch64-linux-gnu-g++ CGO_ENABLED=1 GOOS=linux GOARCH=arm64 GOARM=7 go build -v
本文链接地址:https://const.net.cn/24.html