leveldb::DB* db; leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options,"/tmp/testdb", &db); assert(status.ok()); //write key1,value1 std::string key="key"; std::string value = "value"; status = db->Put(leveldb::WriteOptions(), key,value); assert(status.ok()); status = db->Put(leveldb::WriteOptions(), key,"hello"); assert(status.ok()); status = db->Get(leveldb::ReadOptions(), key, &value); assert(status.ok()); std::cout<<value<<std::endl; std::string key2 = "key2"; //move the value under key to key2 status = db->Put(leveldb::WriteOptions(),key2,value); assert(status.ok()); status = db->Delete(leveldb::WriteOptions(), key); assert(status.ok()); status = db->Get(leveldb::ReadOptions(),key2, &value); assert(status.ok()); std::cout<<key2<<"==="<<value<<std::endl; status = db->Get(leveldb::ReadOptions(),key, &value); if(!status.ok()) std::cerr<<key<<" "<<status.ToString()<<std::endl; else std::cout<<key<<"==="<<value<<std::endl; delete db; return 0; 其他类型的操作: //向数据库插入数据的操作如下: leveldb::DB* LocalCacheDB:: m_pDB=NULL; leveldb::Options LocalCacheDB:: m_options; bool WriteToDB(INFO& info) { leveldb::WriteOptions wo; leveldb::ReadOptions ro; wo.sync = false;//考虑是否异步 //将info转为char[] int nLen = sizeof(INFO); char* chTmp = new char[nLen]; ZeroMemory(chTmp, nLen); memcpy(chTmp,&info, nLen); char chKey[10]; ZeroMemory(chKey, 10); leveldb::Iterator *iter = m_pDB->NewIterator(ro); if (iter == NULL) { return false; } iter->SeekToLast();//last的key最大,这里是自己定义的比较函数按key排序 if (!iter->Valid()) { //数据库为空 itoa(1, chKey, 10);//key从1开始 } else { leveldb::Slice sliceKey; sliceKey=iter->key(); HPR_INT32 nKey=0; nKey=atoi(sliceKey.data()); nKey++; itoa(nKey,chKey,10); } delete iter;//切忌在使用完sliceKey之前删除iter leveldb::Status s = m_pDB->Put(wo,chKey,leveldb::Slice(chTmp,nLen)); delete[] chTmp; if (!s.ok()) { return false; } cout<<"存入一条数据 index:"<<chKey<<endl; return true; } //比较函数如下: class DBComparator:public leveldb::Comparator { public: int Compare(const leveldb::Slice& a, const leveldb::Slice& b) const { int na,nb; na=atoi(a.data()); nb=atoi(b.data()); if (na<nb) { return -1; } if (na>nb) { return +1; } return 0; } // Ignore the following methods for now: const char* Name() const { return "DBComparator"; } void FindShortestSeparator(std::string*, const leveldb::Slice&) const { } void FindShortSuccessor(std::string*) const { } };
leveldb
精选 转载上一篇:联合体结构体
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
NoSQL 数据库管理工具,支持:Redis、Memcached、SSDB、LevelDB、RocksDB
从单一应用程序中同时连接 Redis、Memcached、SSDB、LevelDB、RocksDB,你可以快速轻松地创建、管理和维护数据库。
Redis SSDB Memcached LevelDB RocksDB -
levelDB编译
levelDB简单使用
levelDB