HomePractices Page 3 - Database Independent Development in C
Getting Results - 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.
Once a connection has been established, dbi_conn_query() lets you make a query into the database. dbi_conn_query takes the connection as the first argument and a printf formatted SQL statement as its second argument. The remainder is the standard variable argument list. It is worth noting that at this time the arguments are in no way run through any kind of string escaping function. It's the duty of the programmer to escape any input. The native escaping function of the database library can be obtained with a little work, although at times I have written my own string escaping function.
The return value from dbi_conn_query() is a dbi_result object. You cycle through the result set by using the dbi_result_next_row() function, which takes the result set as its only argument. This function must be called at least once before any actual column results can be extracted. This function returns 0 if there are no more rows in the result set.
To get the values of individual columns, there are a variety of dbi_result_get_datatype functions which take the dbi_result object and the column name as parameters. The most common are dbi_result_get_long and dbi_result_get_string, but they exist for every common data type, including datetime columns (which return a time_t).
Finally, when you are done with the result set and the connection, there are a few cleanup functions. dbi_result_free() frees up the memory used by the result set. dbi_conn_close() will close the database connection, and dbi_shutdown() unloads the database drivers that have been loaded.