我尝试使用键作为字符串将数据插入到leveldb数据库中,然后尝试获取最后一个键,但是问题是当我以字符串格式插入1到11个键时,leveldb将它们布置为字符串并返回错误的数据,所以我需要一种方法来防止leveldb在不更改键格式的情况下对数据进行排序
//this is the struct
values := [10]DataStruct{
{Index: "1"},{Index: "2"},{Index: "3"},{Index: "5"},
{Index: "6"},{Index: "7"},{Index: "8"},{Index: "9"},
{Index: "10"},{Index: "11"},
}
//this is insert func
func Create(data DataStruct) bool {
Opendatabase() //open database
d, convert := marshaltobson(data) // convert to []byte
if !convert {
return false
}
err := db.Put([]byte(data.Index), d, nil)
if err != nil {
return false
}
Closedatabase()
return true
}
// this is get all function
func GetAll() (values []DataStruct) {
Opendatabase()
iter := db.NewIterator(nil, nil)
for iter.Next() {
value := iter.Value()
var newdata DataStruct
json.Unmarshal(value, &newdata)
values = append(values, newdata)
}
Closedatabase()
return values
}
//func to get last key
func Getlast() (Structlst DataStruct) {
Opendatabase()
var result DataStruct
iter := db.NewIterator(nil, nil)
iter.Last()
value := iter.Value()
json.Unmarshal(value, &result)
Closedatabase()
return result
}
var err bool
for i := 0; i < len(values); i++ {
err = Errordb.Create(values[i])
if err {
fmt.Println("worked")
}
}
fmt.Println("---------------------------------- ")
fmt.Println("get all data in database :- ")
fmt.Println("---------------------------------- ")
value := GetAll()
for i := 0; i < len(value); i++ {
fmt.Println(value[i])
fmt.Println("")
}
fmt.Println("---------------------------------- ")
fmt.Println("get last :- ")
fmt.Println("---------------------------------- ")
value1 := Getlast()
// this is the output
----------------------------------
get all data in database :-
----------------------------------
{1}
{10}
{11}
{2}
{3}
{5}
{6}
{7}
{8}
{9}
----------------------------------
get last :-
----------------------------------
{9}