bolt 数据库是一个纯粹用go编写的key/value数据库,这个库的目的是为了提供一个简单,快速可靠的数据库
package main import ( "github.com/boltdb/bolt" "log" "os" "testing" ) // ============================================================================== func p(a ...interface{}) (n int, err error) { return fmt.Print(a...) } func pn(a ...interface{}) (n int, err error) { return fmt.Println(a...) } func pf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, a...) } func pfn(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format+"\n", a...) } // ============================================================================== type DB struct { *bolt.DB name string } func Open(path string, mode os.FileMode, options *bolt.Options) (*DB, error) { db, err := bolt.Open(path, mode, options) return &DB{DB: db, name: "test"}, err } func (db *DB) Name(name string) *DB { db.name = name return db } func (db *DB) Set(k string, v string) *DB { err := db.Update(func(tx *bolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte(db.name)) if err != nil { log.Fatal(err) } return b.Put([]byte(k), []byte(v)) }) if err != nil { log.Fatal(err) } return db } func (db *DB) Get(k string) (string, error) { var v string err := db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte(db.name)) v = string(b.Get([]byte(k))) return nil }) return v, err } func Test(t *testing.T) { db, _ := Open("my-bolt.db", 0644, nil) db.Name("mytest").Set("0", "000").Set("1", "111").Set("2", "222") pn(db.Get("0")) pn(db.Get("1")) pn(db.Get("2")) db.Close() }
标签:return,string,err,示例,DB,db,golang,bolt,func From: https://www.cnblogs.com/zbseoag/p/17111817.html