Go语言中使用 BoltDB数据库

boltdb 是使用Go语言编写的开源的键值对数据库,Github的地址如下:

https://github.com/boltdb/bolt

boltdb 存储数据时 key 和 value 都要求是字节数据,此处需要使用到 序列化和反序列化。

以下为boltdb的常见使用方式:

1、安装Boltdb数据库

使用如下命令进行安装

go get github.com/boltdb/bolt

2、常见API操作

package main
import (
	"github.com/boltdb/bolt"
	"log"
	"fmt"
)
func main()  {
	// Open the my.db data file in your current directory.
	// It will be created if it doesn't exist.
	// 创建或者打开数据库
	db, err := bolt.Open("my.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()


	// 创建表
	err = db.Update(func(tx *bolt.Tx) error {
		// 获取BlockBucket表单
		b := tx.Bucket([]byte("BlockBucket"))

		// 往表里面存储数据
		if b != nil {
			err := b.Put([]byte("ll"),[]byte("Send 1000 BTC To 冠希哥......"))
			if err != nil {
				log.Panic("数据存储失败......")
			}
		}

		// 返回nil,以便数据库处理相应操作
		return nil
	})
	//更新失败
	if err != nil {
		log.Panic(err)
	}

	// 查看数据
	err = db.View(func(tx *bolt.Tx) error {

		// 获取BlockBucket表对象
		b := tx.Bucket([]byte("BlockBucket"))

		// 往表里面存储数据
		if b != nil {
			data := b.Get([]byte("l"))
			fmt.Printf("%s\n",data)
			data = b.Get([]byte("ll"))
			fmt.Printf("%s\n",data)
		}

		// 返回nil,以便数据库处理相应操作
		return nil
	})
	//更新失败
	if err != nil {
		log.Panic(err)
	}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘贤松

一本万利

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值