Database Independent Abstraction Layer for C: libdbi Programmer's Guide (OUTDATED SEE README!) | ||
---|---|---|
Prev | Chapter 2. libdbi in a Nutshell (Quickstart Guide) | Next |
#include <stdio.h> #include <dbi/dbi.h> int main() { dbi_conn conn; dbi_result result; double threshold = 4.333333; unsigned long idnumber; const char *fullname; dbi_initialize(NULL); conn = dbi_conn_new("mysql"); dbi_conn_set_option(conn, "host", "localhost"); dbi_conn_set_option(conn, "username", "chug"); dbi_conn_set_option(conn, "password", "dIP!"); dbi_conn_set_option(conn, "dbname", "db_name"); dbi_conn_connect(conn); result = dbi_conn_query(conn, "SELECT id, name FROM coders " "WHERE hours_of_sleep > %0.2f", threshold); while (dbi_result_next_row(result)) { idnumber = dbi_result_get_ulong(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(); return 0; } |
Compile with: gcc -lm -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.