package main
import (
"fmt"
"github.com/boltdb/bolt"
)
var (
db *bolt.DB
bucket []byte
)
const dbname = "module.db"
func init() {
//创建bolt数据库本地文件
dbc, err := bolt.Open(dbname, 0600, nil)
//初始化bucket
bucket = []byte("demoBucket")
if err != nil {
fmt.Println("open err:", err)
return
} else {
db = dbc
}
//创建bucket
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket(bucket)
return err
})
}
//把数据插入到bolt数据库中,相当于 redis 中的set命令
func insert(key, value string) {
k := []byte(key)
v := []byte(value)
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
err := b.Put(k, v)
return err
})
}
//读取一条数据
func read(key string) string {
k := []byte(key)
var val []byte
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
val = b.Get(k)
return nil
})
return string(val)
}
//遍历指定的bucket中的数据
func fetchAll(buk []byte) {
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(buk)
cur := b.Cursor()
for k, v := cur.First(); k != nil; k, v = cur.Next() {
fmt.Printf("key is %s,value is %s\n", k, v)
}
return nil
})
}
func main() {
defer db.Close()
insert("hello", "Hello World,This is Bolt Database11..")
insert("hello2", "Hello World,This is Bolt Database22..")
fmt.Println(read("hello"))
fmt.Println(read("hello2"))
insert("news1", "this is a title.")
fetchAll(bucket)
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
智能家居:商业模式+案例分析+应用实战
陈国嘉 / 人民邮电出版社 / 2016-4 / 49.80元
作为万物互联的关键一环,智能家居的出现和普及已经势不可当,以移动互联网为核心的新技术正在重构智能家居。只有成为智能家居行业的先行者,才能抢占“风口”。 《智能家居:商业模式+案例分析+应用实战》紧扣“智能家居”,从3个方面进行专业、深层次的讲解。首要方面是基础篇,从智能家居的发展现状、产业链、商业分析、抢占入口等方面进行阐述,让读者对智能家居有个初步的认识;第二个方面是技术篇,从智能家居的控......一起来看看 《智能家居:商业模式+案例分析+应用实战》 这本书的介绍吧!