当前位置: 首页 > 工具软件 > LevelDB.NET > 使用案例 >

leveldb简单使用样例

养研
2023-12-01

个人随笔 (Owed by: 春夜喜雨 http://blog.csdn.net/chunyexiyu)

下面附几个leveldb的简单使用样例,包含写数据、查数据、遍历数据,仅供参考。

写数据

#include "leveldb/db.h"
int main(int argc, char** argv)
{
    if (argc < 2){
        printf("%s dbname\n", argv[0]);
        return -1;
    }
    char* dbname = argv[1];
    leveldb::DB* pDB;
    leveldb::Options opts;
    opts.create_if_missing = true;
    leveldb::Status st = leveldb::DB::Open(opts, dbname, &pDB);
    if (!st.ok()){
        printf("open db<%s> failed: %s\n", dbname, st.ToString().c_str());
        return -1;
    }
    leveldb::WriteOptions wopts;
    for (int i=0; i<20; i++){
       std::string key(3, i+'a'), value(3, i+'A');
       st = pDB->Put(wopts, key, value);
       if (!st.ok()){
           printf("Put <%s-%s> failed!\n", key.c_str(), value.c_str()); 
           return -1;
       }
       printf("Put pair<%s-%s>\n", key.c_str(), value.c_str()); 
    }
    delete pDB;
    return 0;
}

查数据

#include "leveldb/db.h"
int main(int argc, char** argv)
{
    if (argc < 2){
        printf("%s dbname\n", argv[0]);
        return -1;
    }
    char* dbname = argv[1];
    leveldb::DB* pDB;
    leveldb::Options opts;
    leveldb::Status st = leveldb::DB::Open(opts, dbname, &pDB);
    if (!st.ok()){
        printf("open db<%s> failed: %s\n", dbname, st.ToString().c_str());
        return -1;
    }
    leveldb::ReadOptions ropts;
    for (int i=0; i<10; i++){
       std::string key(3, i+'a'), value;
       st = pDB->Get(ropts, key, &value);
       if (!st.ok()){
           printf("Get key<%s> value failed!\n", key.c_str()); 
           return -1;
       }
       printf("Get <%s-%s>\n", key.c_str(), value.c_str()); 
    }    
    delete pDB;
    return 0;
}

遍历数据

#include "leveldb/db.h"
int main(int argc, char** argv)
{
    if (argc < 2){
        printf("%s dbname\n", argv[0]);
        return -1;
    }
    char* dbname = argv[1];
    leveldb::DB* pDB;
    leveldb::Options opts;
    leveldb::Status st = leveldb::DB::Open(opts, dbname, &pDB);
    if (!st.ok()){
        printf("open db<%s> failed: %s\n", dbname, st.ToString().c_str());
        return -1;
    }
    leveldb::Iterator* iter = pDB->NewIterator(leveldb::ReadOptions());
    iter->SeekToFirst();
    int n = 0;
    while(iter->Valid()){
        leveldb::Slice key = iter->key();
        leveldb::Slice value = iter->value();
        printf("%d: (%s -> %s)\n", ++n, key.ToString().c_str(), value.ToString().c_str());
        iter->Next();
    }
    delete iter;
    delete pDB;
    return 0;
}

make编译语句:
g++ -o $@ $^ -lleveldb -std=c++11

个人随笔 (Owed by: 春夜喜雨 http://blog.csdn.net/chunyexiyu)

 类似资料: