#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <qdb/qdb.h>
/**
* This sample program connects to the database and does one INSERT and one SELECT.
* The database's device name is assumed to be /dev/qdb/customerdb, and its schema is:
* CREATE TABLE customers(
* customerid INTEGER PRIMARY KEY AUTOINCREMENT,
* firstname TEXT,
* lastname TEXT
* );
*/
int main(int argc, char **argv) {
int rc;
qdb_hdl_t *hdl;
qdb_result_t *res;
char *errmsg;
// Connect to the database
hdl = qdb_connect("/dev/qdb/customerdb", 0);
if (hdl == NULL) {
fprintf(stderr, "Error connecting to database: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// INSERT a row into the database
rc = qdb_statement(hdl,
"INSERT INTO customers(firstname, lastname) VALUES('Kevin', 'Kunka');");
if (rc == -1) {
errmsg = qdb_geterrmsg(hdl);
fprintf(stderr, "Error executing INSERT statement: %s\n", errmsg);
return EXIT_FAILURE;
}
// SELECT one row from the database--
// this statement combines the first and last names into full names
rc = qdb_statement(hdl,
"SELECT firstname || ' ' || lastname AS fullname FROM customers LIMIT 1;");
if (rc == -1) {
errmsg = qdb_geterrmsg(hdl);
fprintf(stderr, "Error executing SELECT statement: %s\n", errmsg);
return EXIT_FAILURE;
}
// Get the result
res = qdb_getresult(hdl);
if (res == NULL) {
errmsg = qdb_geterrmsg(hdl);
fprintf(stderr, "Error getting result: %s\n", errmsg);
return EXIT_FAILURE;
}
if (qdb_rows(res) == 1) {
printf("Got a customer's full name: %s\n", (char *)qdb_cell(res, 0, 0));
}
else {
printf("No customers in the database!\n");
}
// Free the result
rc = qdb_freeresult(res);
if (rc == -1) {
fprintf(stderr, "Error freeing SQL statement results: %s\n", strerror(errno));
return EXIT_FAILURE;
}
// Disconnect from the server
rc = qdb_disconnect(hdl);
if (rc == -1) {
fprintf(stderr, "Error disconnecting from database: %s\n", strerror(errno));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}