您的位置:首页 > 数据库

LevelDB数据库使用

2011-12-24 15:31 190 查看
向数据库插入数据的操作如下:

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 { }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: