Apples and Oranges, Part II: A Linux DBMS Comparison
Bringing the Client to Life on MySQL

Matthias Warkus
Thursday, November 18, 1999 01:25:46 PM
MySQL's C API is pretty easy to use. The central element is a structure
containing information about, and state of, the database connection, which is
initialized by connecting to the MySQL server. A pointer to this structure must
be passed to all MySQL client functions.
Queries are submitted as strings; this means that one must deal with C's
string conversion facilities. Should data containing null bytes
(\0) be used, the situation becomes more complicated, because a
counted string is then passed instead of a C string.
To fetch a query's result, a pointer to a MYSQL_RES structure
and a count variable are initialized with appropriate API functions, and then
rows are fetched into a MYSQL_ROW variable, which is an array of
strings. Directly putting results into integer variables, as PostgreSQL's
implementation of ESQL could do, is not possible. The result buffer is then
freed. As you can see, the semantics are almost the same as using a cursor in
ESQL.
Here is list_books(), written using MySQL's C API:
list_books(void)
{
int count;
MYSQL_RES *result;
mysql_query(&bookstore, "SELECT ARTICLE_NO, AUTHOR_FIRST_NAMES,\
AUTHOR_LAST_NAMES, TITLE, ISBN, WHOLESALE_PRICE, RETAIL_PRICE,\
COPIES_AVAILABLE FROM BOOK");
result = mysql_store_result(&bookstore);
for(count = mysql_num_rows(result); count > 0; count--)
{
MYSQL_ROW record;
record = mysql_fetch_row(result);
printf("\nArticle no. %s\n", record[0]);
printf("%s, %s:\n", record[2], record[1]);
printf(" %s (%s)\n", record[3], record[4]);
printf("Bought at %s; selling at %s; %s copies available\n\n",
record[5], record[6], record[7]);
};
mysql_free_result(result);
}
The API functions are concisely, but sufficiently, documented in the Texinfo
file that comes as MySQL's main source of documentation.
Next: Bringing the Client to Life on mSQL »