安裝
go get github.com/syndtr/goleveldb/leveldb
使用
1 打開吴趴、創(chuàng)建數(shù)據(jù)庫
db, err := leveldb.OpenFile("./block.db", nil)
2 寫入一個Key數(shù)據(jù)
err = db.Put([]byte("hello"), []byte("world"), nil)
3 讀取一個Key數(shù)據(jù)
data, _ := db.Get([]byte("hello"), nil)
4 遍歷數(shù)據(jù)庫
iter := db.NewIterator(nil, nil)
for iter.Next() {
logger.Debug(iter.Key() + iter.Value())
}
5 讀取某個前綴的所有KEY數(shù)據(jù)
讀出來的數(shù)據(jù)會被放進一個Iterator中书聚。加入數(shù)據(jù)庫現(xiàn)在有key-$num為頭的數(shù)條數(shù)據(jù)
iter := db.NewIterator(dbUtil.BytesPrefix([]byte("key-")), nil)
遍歷讀取這些數(shù)據(jù)
for iter.Next() {
logger.Debug(string(iter.Key()) + string(iter.Value()))
}
讀取最后一條數(shù)據(jù)
if iter.Last() {
logger.Debug(iter.Key() + iter.Value())
}
6 刪除某個KEY
err = db.Delete([]byte("key-3"), nil)