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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| package main
import ( "bytes" "fmt" "github.com/boltdb/bolt" "log" "time" )
func main() { BoltDB() }
func BoltDB(){ db,err := bolt.Open("my.db" , 0600 , &bolt.Options{Timeout: 10*time.Second}) defer db.Close() if err != nil { log.Panic(err) }
err = db.Update(func(tx *bolt.Tx) error { b , err := tx.CreateBucketIfNotExists([]byte("MyBucket")) err = b.Put([]byte("answer") , []byte("42")) err = b.Put([]byte("why") , []byte("101010")) return err
})
err = db.Batch(func(tx *bolt.Tx) error { return nil })
db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("MyBucket")) v := b.Get([]byte("answer")) id , _ := b.NextSequence() fmt.Printf("The answer is : %s,%d\n" , v , id)
c := b.Cursor() fmt.Printf("\n游标遍历key") for k , v := c.First() ; k!=nil;k,v=c.Next(){ fmt.Printf("key = %s , value = %s\n" , k ,v) }
fmt.Printf("\nPrefix 前缀扫描") prefix := []byte("a") for k ,v := c.Seek(prefix);k!=nil&&bytes.HasPrefix(k,prefix);k,v=c.Next(){ fmt.Printf("key = %s , value = %s\n" , k,v) } return nil })
db.View(func(tx *bolt.Tx) error { fmt.Println("\nForEach()来迭代") b := tx.Bucket([]byte("MyBucket")) b.ForEach(func(k, v []byte) error { fmt.Printf("key = %s , value = %s\n" , k ,v) return nil }) return nil })
tx,err := db.Begin(true) if err!=nil{ log.Panic(err) } defer tx.Rollback()
_,err = tx.CreateBucket([]byte("MyBucket")) if err!=nil{ log.Panic(err) }
if err = tx.Commit() ; err != nil{ log.Panic(err) }
}
|