Write record example:
# Include <iostream> # include "db_cxx.h" # define Database "duplicated. DB "# define put_records (keystr, datastr, cursorp, flag) \ do {\ DBT key (keystr, strlen (keystr) + 1); \ DBT data (datastr, strlen (datastr) + 1); \ nret = cursorp-> put (& Key, & Data, flag); \ STD: cout <keystr <"put result: "<nret <STD: Endl ;\} while (0); int main () {dB my_database (null, 0); DBC * cursorp; int nret = 0; try {// set databa Se flagsmy_database.set_flags (db_dupsort); // set duplicate records that support sorting in the database. // open databasemy_database.open (null, database, null, db_btree, db_create, 0664 ); // open records (null, & cursorp, 0); put_records ("Alabama", "Athens", cursorp, db_keyfirst); put_records ("Alabama", "Florence", cursorp, db_keyfirst); put_records ("Alaska", "anchorage", cursorp, db_keyfirst); put_records ("Alaska", "Fairbanks ", Cursorp, db_keyfirst); put_records ("Arizona", "Florence", cursorp, db_keyfirst);} catch (dbexception & E) {STD: cout <"DB exception: "<E. what () <STD: Endl;} catch (STD: exception & E) {STD: cout <"STD: exception:" <E. what () <STD: Endl;} If (cursorp! = NULL) cursorp-> close (); my_database.close (0); Return 0 ;}
Example of reading records:
#include <iostream>#include <db_cxx.h>#include <string>#define DATABASE "duplicated.db"int main(){Db my_database(NULL, 0);Dbc* cursorp = NULL;int nRet = 0;try {// open databasemy_database.open(NULL, DATABASE, NULL, DB_BTREE, DB_RDONLY, 0664);// open cursormy_database.cursor(NULL, &cursorp, 0);Dbt key1, data1;// print all recordswhile ((nRet = cursorp->get(&key1, &data1, DB_NEXT)) != DB_NOTFOUND) {std::cout << (char*)key1.get_data() << " " << (char*)data1.get_data() << std::endl;}}catch (DbException& e) {std::cout << "db exception: " << e.what() << std::endl;}catch (std::exception &e) {std::cout << "std::exception: " << e.what() << std::endl;}if (cursorp != NULL)cursorp->close();my_database.close(0);}
Output result:
Alabama Athens
Alabama Florence
Alaska Anchorage
Alaska Fairbanks
Arizona Florence
Press any key to continue