Saturday, May 31, 2008

Simple example: using the MySQL C API

Here we present a very simple example illustrating how to access a MySQL database using the C API. Here we connect to a MySQL database called test_db on a host with IP address 192.168.0.1, username "user", and password "pass". A simple query is executed, and the results printed.
#include <mysql.h>
#include <stdio.h>
#include <iostream>

MYSQL *conn;

using namespace std;

int main(int argc, char *argv[])
{

// initialize a MYSQL object

conn = mysql_init(NULL);

if (conn == NULL)
{
cerr << "ERROR: mysql_init failed" << endl;
exit(1);
}

// connect to the MySQL database

if (mysql_real_connect(conn, "192.168.0.1", "user", "pass",
"test_db", 0, NULL, 0) == NULL)
{
cerr << "ERROR: mysql_real_connect() failed" << endl;
exit(1);
}

// define a query

char *query = "SELECT * from my_table;";

if (mysql_query (conn, query) != 0)
{
cerr << "ERROR: mysql_query failed" << endl;
exit(1);
}
else
{

// initiate a result set retrieval

MYSQL_RES *res_set;
res_set = mysql_use_result(conn);
if (res_set == NULL)
{
cerr << "ERROR: mysql_use_result failed" << endl;
exit(1);
}
else
{
MYSQL_ROW row;

// retrieve a row of data from the result set

while ((row = mysql_fetch_row(res_set)) != NULL)
{

// print the results for the current row

for (int i=0; i<mysql_num_fields(res_set); i++)
{
cout << row[i] << " ";
}
cout << endl;
}
}
}

// de-allocate memory

mysql_free_result(res_set);

// close the MySQL connection

mysql_close(conn);
}

Here we have used mysql_use_result. This initiates a result set retrieval, but does not actually retrieve the data. This must be done for each row using mysql_fetch_row. An alternative is to use mysql_store_result instead of mysql_use_result, which reads the entire set of results into memory.

No comments: