Debian Codegraph @

examples/cxx/getting_started/MyDb.cpp

raw
1 /*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2004, 2013 Oracle and/or its affiliates. All rights reserved.
5 *
6 * $Id$
7 */
8
9 #include "MyDb.hpp"
10
11 // File: MyDb.cpp
12
13 // Class constructor. Requires a path to the location
14 // where the database is located, and a database name
15 MyDb::MyDb(std::string &path, std::string &dbName,
16 bool isSecondary)
17 : db_(NULL, 0), // Instantiate Db object
18 dbFileName_(path + dbName), // Database file name
19 cFlags_(DB_CREATE) // If the database doesn't yet exist,
20 // allow it to be created.
21 {
22 try
23 {
24 // Redirect debugging information to std::cerr
25 db_.set_error_stream(&std::cerr);
26
27 // If this is a secondary database, support
28 // sorted duplicates
29 if (isSecondary)
30 db_.set_flags(DB_DUPSORT);
31
32 // Open the database
33 db_.open(NULL, dbFileName_.c_str(), NULL, DB_BTREE, cFlags_, 0);
34 }
35 // DbException is not a subclass of std::exception, so we
36 // need to catch them both.
37 catch(DbException &e)
38 {
39 std::cerr << "Error opening database: " << dbFileName_ << "\n";
40 std::cerr << e.what() << std::endl;
41 }
42 catch(std::exception &e)
43 {
44 std::cerr << "Error opening database: " << dbFileName_ << "\n";
45 std::cerr << e.what() << std::endl;
46 }
47 }
48
49 // Private member used to close a database. Called from the class
50 // destructor.
51 void
52 MyDb::close()
53 {
54 // Close the db
55 try
56 {
57 db_.close(0);
58 std::cout << "Database " << dbFileName_
59 << " is closed." << std::endl;
60 }
61 catch(DbException &e)
62 {
63 std::cerr << "Error closing database: " << dbFileName_ << "\n";
64 std::cerr << e.what() << std::endl;
65 }
66 catch(std::exception &e)
67 {
68 std::cerr << "Error closing database: " << dbFileName_ << "\n";
69 std::cerr << e.what() << std::endl;
70 }
71 }