C++ examples of leveldb

LevelDB is a kind of key-value C++ database developped by Google engineers.

My installation script is simple on Arch Linux:

1
sudo pacman -Syu leveldb

Example 1

We create and then delete a leveldb database instance. Another important thing is to learn how to build with leveldb dynamic link library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <assert.h>
#include "leveldb/db.h"

using namespace std;

int main(void)
{
leveldb::DB *db;
leveldb::Options options;
options.create_if_missing = true;

leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());

delete db;

return 0;
}

compile and link: g++ test-leveldb.cc -Iinclude -l:libleveldb.so

-Iinclude means searching *.h files under /usr/include, so that we can write the relevant referencing path as #include <leveldb/db.h> since the full path of the header file is /usr/include/leveldb/db.h. By default /usr/include is included by gcc. Therefore, omitting -Iinclude is also acceptable.

-l:libleveldb.so means searching for libleveldb.so under link library path, which by default is /usr/lib/. -l:libleveldb.so also has a shorten form: -lleveldb.

Example 2

Create, Delete, Update, Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <assert.h>
#include "leveldb/db.h"

using namespace std;

int main(void)
{
leveldb::DB *db;
leveldb::Options options;
options.create_if_missing = true;

// open
leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());

string key = "name";
string value = "shane";

// write
status = db->Put(leveldb::WriteOptions(), key, value);
assert(status.ok());

// read
status = db->Get(leveldb::ReadOptions(), key, &value);
assert(status.ok());

cout << value << endl;

// delete
status = db->Delete(leveldb::WriteOptions(), key);
assert(status.ok());

status = db->Get(leveldb::ReadOptions(), key, &value);
if (!status.ok()) {
cerr << key << " " << status.ToString() << endl;
} else {
cout << key << "===" << value << endl;
}

//close
delete db;

return 0;
}

compile and link as example 1 shows.
run ./a.out. /tmp/testdb will appear:

Here we can notice that even though db is deleted, the files created under /tmp/cduq-db are still exist. If you want to delete this file, we can use leveldb::DestroyDB.

LevelDB Structure:
leveldb-struct.png

Creating virtual machiness on Linux --- the hard way FreeBSD survival manual

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×