# Generic Example Program

The following listing shows how to establish a connection to a MySQL database server and retrieve the results of a SQL query. Only a small number of functions offered by libdbi are shown here. For a more extensive example check out the test program `tests/test_dbi.c` in the libdbi-drivers source tarball.

    #include <stdio.h>
    #include <dbi/dbi.h>

    int main() {
        dbi_conn conn;
        dbi_result result;
        dbi_inst instance;

        double threshold = 4.333333;
        unsigned int idnumber;
        const char *fullname;

        dbi_initialize_r(NULL, &instance);
        conn = dbi_conn_new_r("mysql", instance);

        dbi_conn_set_option(conn, "host", "localhost");
        dbi_conn_set_option(conn, "username", "your_name");
        dbi_conn_set_option(conn, "password", "your_password");
        dbi_conn_set_option(conn, "dbname", "your_dbname");
        dbi_conn_set_option(conn, "encoding", "UTF-8");

        if (dbi_conn_connect(conn) < 0) {
          printf("Could not connect. Please check the option settings\n");
        }
        else {
          result = dbi_conn_queryf(conn, "SELECT id, name FROM coders "
                                      "WHERE hours_of_sleep > %0.2f", threshold);

          if (result) {
    	while (dbi_result_next_row(result)) {
    	  idnumber = dbi_result_get_uint(result, "id");
    	  fullname = dbi_result_get_string(result, "name");
    	  printf("%i. %s\n", idnumber, fullname);
    	}
    	dbi_result_free(result);
          }
          dbi_conn_close(conn);
        }

        dbi_shutdown_r(instance);

        return 0;
    }

Compile with: gcc -lm -ldl -ldbi -o foo foo.c

The `-ldl` option is not required on systems that implement the dynamic linking in their libc (like FreeBSD). You may also have to throw in something like `-I/usr/local/include` and `-L/usr/local/lib` to help gcc and ld find the libdbi headers and libraries.

Of course, a complete program should check for errors more thoroughly. This example keeps error-checking at a minimum for the sake of clarity. There are also other ways to retrieve data after a successful query. Keep reading on to see the rest.

## Loading libdbi at runtime

The generic example shown in the previous section assumed that the program is linked against libdbi. This is in fact the recommended way to add libdbi functionality to your programs. However, there are situations where this approach will not work. Some programs are designed to load modules at runtime to extend their capabilities. A well-known example is the web server Apache, which uses loadable modules to custom-tailor its capabilities. If such a module were to use libdbi, we'd look at the following pattern:

Parent => dl_open(module) => dl_open(driver)

The dynamically loaded module is linked against libdbi whereas the parent application is not. For this pattern to work, the drivers are linked against libdbi by default. This avoids "undefined symbol" errors at runtime, but may cause problems under arcane conditions or on equally arcane operating systems. If you should ever encounter such problems, you can switch off linking the drivers against libdbi like this:

    ~/libdbi-drivers #./configure --disable-libdbi --with-mysql

## Using libdbi in multithreaded applications

With some precautions, libdbi can be used in multithreaded applications. One way to do this is to initialize separate libdbi instances in each thread. If this is not an option and several threads have to share a single instance, you currently need to protect certain libdbi function calls with mutexes. These functions are dbi-conn-query, dbi-conn-ping, and dbi-conn-error.

## Adding libdbi to your project

If your project uses autoconf to manage the build process on the target machine, you should add some tests to your `./configure` script to check for the presence and usability of libdbi. The following example shows how this can be done:

    dnl check for dynamic linking functions
    AC_CHECK_LIB(dl,dlopen)

    dnl check for the libdbi library
    AC_CHECK_LIB(dbi,dbi_initialize)

    dnl to check for the availability and function of a particular
    dnl driver we need a runtime check (since the driver is loaded
    dnl dynamically). This example checks for the mysql driver
    AC_MSG_CHECKING("for libdbi mysql driver (dynamic load)")
    AC_RUN_IFELSE(
      [AC_LANG_PROGRAM(,
        [[dbi_initialize(0); return(dbi_conn_new("mysql") ? 0 : 1);]])],
      [AC_MSG_RESULT("yes")],
      [AC_MSG_FAILURE("mysql driver not installed?")])

The first two tests add the appropriate flags to the `LIBS` variable to link against the required libraries.

In addition, you have to make sure that both the directory which contains the libdbi header file directory (usually `/usr/include` or `/usr/local/include`) as well as the directory which contains the libdbi library (usually `/usr/lib` or `/usr/local/lib`) are accessible to the compiler and to the linker by using the `-I` and `-L` compiler flags, respectively.