OpenDBX/C API/Usage
Using the library
Using the interface is fairly easy and pretty straight forward: Connect to your database, send your query, retrieve the result set and process the row values. After you've done that you can continue to send queries. If you've finished your job, you have to disconnect from the database and clean up all resources.
Sometimes there may occur an error somewhere, which you will be informed by a return value of the called function smaller than zero. The meanings of the error codes are listed in odbx.h and you get a textual explanation of it if you feed odbx_error() with the return value. A return value of -1 is handled a little bit special internally because then the native database library is asked directly what's wrong
Dealing with connections
You need to setup a connection to your database before you can send queries to the DataBase Management System. Before the connection can be established, the chosen backend must be loaded and all necessary data structures initialized. You don't have to worry about specific details because odbx_init() handles everything for you:
int err; odbx_t* handle; if( ( err = odbx_init( &handle, "mysql", "127.0.0.1", "" ) ) < 0 ) { fprintf( stderr, "odbx_init(): %s\n", odbx_error( handle, err ) ); odbx_finish( handle ); return err; }
SQLite is a little bit different because there is no dedicated server you can connect to. Instead, the database is a file the SQLite library is operating on. Therefore you have to specify the path to the directory (without the file name but with trailing slash or backslash) as third parameter instead. The last parameter doesn't matter in this case. Most other backends will use their default port if the fourth parameter of odbx_init() is empty. If an error occurs you have to call odbx_finish() to avoid memory leaks.
Opening the connection to the database is done by calling odbx_bind_simple() with the initialized handle, the database name and the credentials. The backend will either open an ip connection to the DBMS and authenticates itself by using the user name and password or the SQLite backend opens a file directly. The SQLite library also doesn't use the credentials because it relies on the access control provided by the file system.
if( ( err = odbx_bind_simple( handle, "testdb", "testuser", "testpwd" ) ) < 0 ) { fprintf( stderr, "odbx_bind_simple(): %s\n", odbx_error( handle, err ) ); odbx_finish( handle ); return err; }
Sometimes it may be necessary to switch to another database or reauthenticate using different credentials. You can do this by calling odbx_bind_simple() again, but you have to close the connection with odbx_unbind() before.
if( ( err = odbx_unbind( handle ) ) < 0 ) { fprintf( stderr, "odbx_unbind(): %s\n", odbx_error( handle, err ) ); odbx_finish( handle ); return err; }
I also strongly recommend to unbind before you terminate your programme.
odbx_finish( handle );