设为首页 加入收藏

TOP

LevelDB数据库使用
2014-11-24 08:24:04 来源: 作者: 【 】 浏览:2
Tags:LevelDB 数据库 使用

数据库插入数据的操作如下:

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 www.2cto.com

leveldb::Status s = m_pDB->Put(wo,chKey,leveldb::Slice(chTmp,nLen));
delete[] chTmp;
if (!s.ok())
{

return false;
}
cout<<"存入一条数据 index:"< 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 {
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 { }
};

摘自 我是榜样的博客

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Oracle 11g: The difference betw.. 下一篇Mongodb操作详解(一)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·一篇说人话的文章, (2025-12-27 07:50:09)
·Python Web框架哪家 (2025-12-27 07:50:06)
·基于Python的数据分 (2025-12-27 07:50:03)
·深入理解 Java 集合 (2025-12-27 07:22:48)
·Java集合框架全面解 (2025-12-27 07:22:45)