How to Use BoltDB / bbolt in Go

Use BoltDB in Go by opening a file, creating buckets in transactions, and storing key-value pairs with Put and Get methods.

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))
}
  1. Open the database file with bolt.Open("test.db", 0600, nil) to get a handle.
  2. Start a write transaction using db.Update to create a bucket or modify data.
  3. Create a bucket inside the transaction with tx.CreateBucketIfNotExists([]byte("mybucket")).
  4. Save data by calling b.Put([]byte("key"), []byte("value")) on the bucket.
  5. Read data by starting a read-only transaction with db.View and calling b.Get([]byte("key")).
  6. Always close the database handle with defer db.Close() when finished.