golang leveldb 遍历数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main
import (
"fmt"
"github.com/syndtr/goleveldb/leveldb"
)
func main() {
db, err := leveldb.OpenFile("gossip.db", nil)
if err != nil {
fmt.Println(err)
return
}
for i := 1; i < 10; i++ {
err = db.Put([]byte(fmt.Sprintf("key-%d", i)), []byte(fmt.Sprintf("value-%d", i)), nil)
if err != nil {
fmt.Println(err)
return
}
}
iter := db.NewIterator(nil, nil)
for iter.Next() {
// Remember that the contents of the returned slice should not be modified, and
// only valid until the next call to Next.
key := iter.Key()
value := iter.Value()
fmt.Println(string(key), string(value))
}
iter.Release()
err = iter.Error()
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
}
运行输出:
1
2
3
4
5
6
7
8
9
key-1 value-1
key-2 value-2
key-3 value-3
key-4 value-4
key-5 value-5
key-6 value-6
key-7 value-7
key-8 value-8
key-9 value-9
再举个栗子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"log"
)
func main() {
db, err := leveldb.OpenFile("/tmp/foo.db", nil)
if err != nil {
log.Fatal("Yikes!")
}
defer db.Close()
// err = db.Put([]byte("fizz"), []byte("buzz"), nil)
// err = db.Put([]byte("fizz2"), []byte("buzz2"), nil)
// err = db.Put([]byte("fizz3"), []byte("buzz3"), nil)
iter := db.NewIterator(nil, nil)
for iter.Next() {
key := iter.Key()
value := iter.Value()
fmt.Printf("key: %s | value: %s\n", key, value)
}
fmt.Println("\n")
for ok := iter.Seek([]byte("fizz2")); ok; ok = iter.Next() {
key := iter.Key()
value := iter.Value()
fmt.Printf("key: %s | value: %s\n", key, value)
}
fmt.Println("\n")
for ok := iter.First(); ok; ok = iter.Next() {
key := iter.Key()
value := iter.Value()
fmt.Printf("key: %s | value: %s\n", key, value)
}
iter.Release()
err = iter.Error()
}
本文网址: https://golangnote.com/topic/79.html 转摘请注明来源