天天看點

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

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

};