| 1 | #include <iostream> |
| 2 | #include <lmdb++.h> |
| 3 | |
| 4 | int main() { |
| 5 | /* Create and open the LMDB environment: */ |
| 6 | auto env = lmdb::env::create(); |
| 7 | env.set_mapsize(1UL * 1024UL * 1024UL * 1024UL); /* 1 GiB */ |
| 8 | env.open("./example.mdb/", 0, 0664); |
| 9 | lmdb::dbi dbi; |
| 10 | |
| 11 | // Get the dbi handle, and insert some key/value pairs in a write transaction: |
| 12 | { |
| 13 | auto wtxn = lmdb::txn::begin(env); |
| 14 | dbi = lmdb::dbi::open(wtxn, nullptr); |
| 15 | |
| 16 | dbi.put(wtxn, "username", "jhacker"); |
| 17 | dbi.put(wtxn, "email", std::string("[email protected]")); |
| 18 | dbi.put(wtxn, "fullname", std::string_view("J. Random Hacker")); |
| 19 | |
| 20 | wtxn.commit(); |
| 21 | } |
| 22 | |
| 23 | // In a read-only transaction, get and print one of the values: |
| 24 | { |
| 25 | auto rtxn = lmdb::txn::begin(env, nullptr, MDB_RDONLY); |
| 26 | |
| 27 | std::string_view email; |
| 28 | if (dbi.get(rtxn, "email", email)) { |
| 29 | std::cout << "The email is: " << email << std::endl; |
| 30 | } else { |
| 31 | std::cout << "email not found!" << std::endl; |
| 32 | } |
| 33 | } // rtxn aborted automatically |
| 34 | |
| 35 | // Print out all the values using a cursor: |
| 36 | { |
| 37 | auto rtxn = lmdb::txn::begin(env, nullptr, MDB_RDONLY); |
| 38 | |
| 39 | { |
| 40 | auto cursor = lmdb::cursor::open(rtxn, dbi); |
| 41 | |
| 42 | std::string_view key, value; |
| 43 | if (cursor.get(key, value, MDB_FIRST)) { |
| 44 | do { |
| 45 | std::cout << "key: " << key << " value: " << value << std::endl; |
| 46 | } while (cursor.get(key, value, MDB_NEXT)); |
| 47 | } |
| 48 | } // destroying cursor before committing/aborting transaction (see below) |
| 49 | } |
| 50 | |
| 51 | return 0; |
| 52 | } // enviroment closed automatically |