Step 1: Connecting to the Database
This step shows how to connect to the RDBMS and disconnect when leaving the application.
The code is presented, beginning with the main part:
IldDbms* dbms = IldNewDbms(dbName, connStr) ;
This is the only entry point to the library. A single entry point simplifies the use of the library. Using the IldNewDbms method is all that is required to get connected, and is the only way to get a connection. Any object used later will be allocated from the IldDbms instance returned by this method. Therefore, destroying the IldDbms instance will also automatically release all objects allocated with this instance.
This method has 2 arguments. The first identifies the RDBMS to connect to. There is a specific name for each RDBMS supported by DB Link. The second argument specifies the user name, password, and database identification. Both these arguments are given as parameters to the program.
The connection string format depends on the RDBMS, as described in the following table:
dbName |
connStr |
informix |
userName/password/database@dbServer |
mssql |
userName/password/database/dbServer |
odbc |
dataSourceName/userName/password |
OLE DB |
userName/password/database/dbServer |
oracle |
userName/password@service |
sybase |
userName/password/database/dbServer |
It is possible for the connection to fail. This is the case, for instance, when the user password is incorrect. The following code tests for such a failure:
if (dbms->isErrorRaised()) {
IldDisplayError("Connection failed : ", dbms) ;
delete dbms ;
exit(1) ;
}
The IldDbms class can indicate whether an error occurred and what kind of error it was. The IldDisplayError function queries the IldDbms instance to get this information and then process it (display it in this case). This is done as follows:
void IldDisplayError(const char* operation, const IldIldBase* ildobj) {
cout << operation << endl;
cout << " Code : " << ildobj->getErrorCode() << endl;
cout << " SqlState: " << ildobj->getErrorSqlstate() << endl;
cout << " Message : " << ildobj->getErrorMessage() << endl;
}
Before exiting the program, the IldDbms object must be deleted. Doing so automatically disconnects from the database and releases any objects previously allocated with this connection. This is done very simply, as follows:
delete dbms;
Conclusion
This chapter showed how to connect to an RDBMS and process the errors that may occur. You are now ready to send queries to the server.
See source code.