golang通过mattn/go-sqlite3访问BDB
依赖包
- BDB运行环境
$ tree -L 1 bdb
bdb
|-- bin
|-- docs
|-- include
|-- lib
`-- share
- mattn/go-sqlite3库
$ export GOPATH=$(pwd)
$ go get mattn/go-sqlite3
$ ls -l src/github.com/mattn/go-sqlite3
主程序
package main
import (
"fmt"
"log"
"database/sql"
"github.com/mattn/go-sqlite3"
)
func main() {
sqlDriver := "sqlite3_with_extensions"
fullDBPath := "data/test.db"
sql.Register("sqlite3_with_extensions",
&sqlite3.SQLiteDriver{
Extensions: []string{
"sqlite3_mod_regexp",
},
})
// Open database
db, err := sql.Open(sqlDriver, fullDBPath)
if err != nil {
log.Fatal(err)
}
// Exec
db.SetMaxIdleConns(200)
db.SetMaxOpenConns(200)
_, err = db.Exec("PRAGMA page_size = 8192; PRAGMA synchronous = normal;")
if err != nil {
db.Close()
log.Fatal(err)
}
// Query
rows, err := db.Query("select key, value from mytable")
if err != nil {
db.Close()
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var key string
var value string
err = rows.Scan(&key, &value)
if err != nil {
db.Close()
log.Fatal(err)
}
fmt.Println(key, value)
}
err = rows.Err()
if err != nil {
db.Close()
log.Fatal(err)
}
db.Close()
}
Makefile文件
all: testbdb
testbdb: main.go
LIBRARY_PATH=$(abspath bdb/lib) \
LD_LIBRARY_PATH=$(abspath bdb/lib) \
LD_RUN_PATH=$(abspath bdb/lib) \
C_INCLUDE_PATH=$(abspath bdb/include) \
GOPATH=$(abspath .) \
go build -tags "libsqlite3"
.PHONY: clean
clean:
rm -f testbdb
编译完之后我们看:
$ ldd testbdb
linux-vdso.so.1 => (0x00007ffd4abd2000)
libsqlite3.so => /fullpathto/bdb/lib/libsqlite3.so (0x00007f5b184af000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f5b18282000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f5b18066000)
libc.so.6 => /lib64/libc.so.6 (0x00007f5b17c99000)
/lib64/ld-linux-x86-64.so.2 (0x000055ba571b3000)
而如果我们编译的时候去掉-tags "libsqlite3"选项:
$ ldd testbdb
linux-vdso.so.1 => (0x00007ffcddfda000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007f7945fb2000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f7945d95000)
libc.so.6 => /lib64/libc.so.6 (0x00007f79459c8000)
/lib64/ld-linux-x86-64.so.2 (0x000055b751f99000)
此时testbdb的动态链接库里面没有libsqlite3.so,因此此时采用的是静态连接方法。
有疑问加站长微信联系(非本文作者)