Initialize a BoltDB database with bolt.Open, create buckets within transactions, and store key-value pairs using Put.
package main
import (
"fmt"
"github.com/boltdb/bolt"
)
func main() {
db, err := bolt.Open("test.db", 0600, nil)
if err != nil { return }
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte("mybucket"))
if err != nil { return err }
return b.Put([]byte("key"), []byte("value"))
})
if err != nil { return }
var val []byte
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("mybucket"))
val = b.Get([]byte("key"))
return nil
})
fmt.Println(string(val))
}
- Open the database file with
bolt.Open("test.db", 0600, nil)to get a handle. - Start a write transaction using
db.Updateto create a bucket or modify data. - Create a bucket inside the transaction with
tx.CreateBucketIfNotExists([]byte("mybucket")). - Save data by calling
b.Put([]byte("key"), []byte("value"))on the bucket. - Read data by starting a read-only transaction with
db.Viewand callingb.Get([]byte("key")). - Always close the database handle with
defer db.Close()when finished.