Getting a Connection
To begin, let's log on.
In the old days, connecting to a database was more or less a matter of opening a few files. These days, the complications of networking, RDBMSs, client/server computing, and a host of other considerations have made database connection a major hurdle to overcome in building applications. The DB Interface Module simplifies the process. Using this module, you establish a database connection by requesting an
RWDBDatabase instance from the
RWDBManager.
The DB Interface Module is designed to provide a single, global instance of the class
RWDBManager.
RWDBManager is responsible for providing your applications with correctly typed
RWDBDatabase objects, based upon parameters provided to its static
database() member function.
The following example shows how to establish connectivity using the DB Interface Module. Unlike the code fragments you have seen so far, this is a complete program. After changing the parameters in the database() call to fit your system, you can and should compile and run this program before you attempt anything more ambitious. Remember that you must first establish connectivity without the DB Interface Module, or this program may not work. To use this code, the <ver> placeholder in any library names would need to be replaced with the actual digits representing the library version number.
Example 1 – Establishing connectivity
// Example Program 1 - Establishing connectivity
#include <rw/rstream.h>
#include <rw/db/db.h>
int
main() {
RWDBDatabase myDbase = RWDBManager::database(
"libctl<ver>15d.so", // access module name //1
"sybase_server", // server name //2
"user", // user name //3
"pwd", // password //4
"DEMO_DB" // database name //5
);
if (myDbase.isValid()) {
std::cout << "Connected!" << std::endl;
}
else {
std::cout << myDbase.status().message() << std::endl;
}
return 0;
}
Let's look at the parameters for the RWDBManager::database() call:
NOTE: SourcePro DB supports both static and dynamic linking of access modules.
RWDBManager is responsible for dealing with the operating system details of runtime loading of dynamic libraries, including the important detail of deciding whether to load any libraries at all.
It is also possible to establish multiple login sessions to a database. The information you provide in the RWDBManager::database() call is retained in each database object, so that you don't have to repeat it every time.
When you can successfully run the example program above and obtain an
RWDBDatabase whose
isValid() member function returns
true, you can be confident that:
The Access Module you specified has been located.
An
RWDBConnection object has been successfully instantiated and reserved by the database object for use as a default connection.
In other words, your database connectivity has been established, and you are ready to continue.