對於本地化的Key-value存儲引擎來說,簡單的使用一般都分成三個基本的步驟:(1)打開一個數據庫實例;(2)對這個數據庫實例進行插入,修改和查詢操作;(3)最後在使用完成之後,關閉該數據庫。
Opening A Database
A leveldb database has a name which corresponds to a file system directory. All of the contents of database are stored in this directory. The following example shows how to open a database, creating it if necessary:#include <assert>
#include "leveldb/db.h"
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());
...
If you want to raise an error if the database already exists, add the following line before the leveldb::DB::Open call:
options.error_if_exists = true;
Status
You may have noticed the leveldb::Status type above. Values of this type are returned by most functions in leveldb that may encounter an error. You can check if such a result is ok, and also print an associated error message:leveldb::Status s = ...;
if (!s.ok()) cerr << s.ToString() << endl;
Closing A Database
When you are done with a database, just delete the database object. Example:... open the db as described above ...
... do something with db ...
delete db;
Reads And Writes
The database provides Put, Delete, and Get methods to modify/query the database. For example, the following code moves the value stored under key1 to key2.std::string value;
leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
if (s.ok()) s = db->Put(leveldb::WriteOptions(), key2, value);
if (s.ok()) s = db->Delete(leveldb::WriteOptions(), key1);
測試程序示例
#include <assert.h>
#include <iostream>
#include "leveldb/db.h"
using namespace std;
using namespace leveldb;
int main()
{
DB* db;
Options options;
options.create_if_missing = true;
//options.error_if_exists = true;
Status status = DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());
cout << status.ToString() << endl;
string key1 = "hdu1", value1 = "123";
string key2 = "hdu2", value2 = "456";
string value;
db->Put(WriteOptions(), key1, value1);
db->Put(WriteOptions(), key2, value2);
status = db->Get(ReadOptions(), key1, &value);
if (status.ok())
status = db->Put(WriteOptions(), key2, value);
//if (status.ok())
// status = db->Delete(WriteOptions(), key1);
status = db->Get(ReadOptions(), key1, &value);
if (status.ok())
cout << key1 << ": " << value << endl;
status = db->Get(ReadOptions(), key2, &value);
if (status.ok())
cout << key2 << ": " << value << endl;
delete db;
return 0;
}
編譯程序
命令:g++ -o test test.cpp /home/luox28/leveldb/libleveldb.a -I/home/luox28/leveldb/include -lpthread
當然,在下載好了leveldb源碼後,進入到leveldb主目錄,編譯源碼。 cd leveldb && make all參考資料
1、leveldb自帶doc文檔