HomePractices Page 2 - Database Independent Development in C
Making the Connection - Practices
The libdbi library provides a feature for C programmers that has long been missing. The interface is clean and the framework for adding new drivers is relatively straightforward.
The library is simplicity itself to use, somewhat reminiscent of the PEAR::DB classes in PHP. The two basic data types are dbi_conn, to represent a database connection, and dbi_result, to represent a database result set. Both are typedefs for a void*.
When your program is first initialized, no database drivers are loaded. It will happily execute queries and send you back empty result sets. You initialize drivers in two steps.
First, a call to dbi_initialize() will enumerate the available drivers to the library. The argument can technically be NULL, causing the library to look in the default location. My experience has been, however, that you need to explicitly specify the folders where the drivers reside. In the default installation, or at least on my system, that is /usr/local/lib/dbd. The return value will be the number of drivers found. If 0 drivers are found, check that you specified the correct folder. If the folder is correct, make sure that you created the links to the actual shared libraries in the folder.
Once drivers have been initialized, a database object is created by calling dbi_conn_new(). The argument is the character string that describes the driver, and corresponds to the folder names in the libdbi-drivers/drivers folder. The return object is a uninitialized connection object, waiting for you to supply the connection parameters.
Parameters are set by calling dbi_conn_set_option() with the connection object, the parameter, and the parameter's value. Common parameter names are host, username, password and dbname. For the sqlite driver, the first three are omitted and sqlite_dbdir is used instead. Examples are provided below which should clarify the parameters.
Finally, a connection is opened with dbi_conn_connect(), with the now initialized connection object as the only parameter.