Database Independent Abstraction Layer for C: libdbi Programmer's Guide | ||
---|---|---|
Prev | Chapter 2. libdbi in a Nutshell (Quickstart Guide) | Next |
#include <stdio.h> #include <dbi/dbi.h> int main() { dbi_driver driver; dbi_result result; double threshold = 4.333333; unsigned int idnumber; const char *fullname; dbi_initialize(NULL); driver = dbi_driver_new("mysql"); dbi_driver_set_option(driver, "host", "localhost"); dbi_driver_set_option(driver, "username", "chug"); dbi_driver_set_option(driver, "password", "dIP!"); dbi_driver_set_option(driver, "dbname", "db_name"); dbi_driver_connect(driver); result = dbi_driver_query(driver, "SELECT id, name FROM coders" "WHERE hours_of_sleep > %0.2f", threshold); while (dbi_result_next_row(result)) { idnumber = dbi_result_get_long(result, "id"); fullname = dbi_result_get_string(result, "name"); printf("%i. %s\n", idnumber, fullname); } dbi_result_free(result); dbi_driver_close(driver); dbi_shutdown(); return 0; } |
Compile with: gcc -ldl -ldbi -o foo foo.c
Of course, a complete program should be checking for errors. This example omits error-checking for the sake of clarity. There are also other ways to retrieve data after a successful query. Keep reading on to see the rest.