A Short C API Example

Listing G.1 demonstrates a short sample usage of the C API with the basic components for returning data from the database. You'll need to compile and run it. Compilation instructions will differ from system to system, but could look something like this:

gcc -o example example.c -I/usr/local/mysql/include/mysql–  -L/usr/local/mysql/lib/mysql -lmysqlclient -lz 

Listing G.1: example.c

start example
#include <stdio.h> #include <mysql.h> /* the two basic includes */    /* the main function */ int main(char **args) {   MYSQL_RES *query_result;   MYSQL_ROW row; /* db_handle is the connection to the database, and will be used by  many of the functions that follow */   MYSQL *db_handle, mysql;   int query_error;       /* initialize and open the connection */   mysql_init(&mysql);   db_handle = mysql_real_connect(&mysql,"localhost", "guru2b",–    "g00r002b", "firstdb", 0, 0, 0);   /* if the connection failed, then display the error and exit. */   if (db_handle == NULL) {     printf(mysql_error(&mysql));     return 1;   }   query_error = mysql_query(db_handle,"SELECT first_name,surname FROM customer");   /* if the query error is not 0 (no error), display the error and exit */   if (query_error != 0) {     printf(mysql_error(db_handle));     return 1;   }   /* Return a query result */   query_result = mysql_store_result(db_handle);   /* Loop through and display each row in the query result */   while (( row = mysql_fetch_row(query_result)) != NULL ) {     printf("Name: %s %s\n",(row[0] ? row[0] : "NULL"),–     (row[1] ? row[1] : "NULL"));   }   /* free the resources associated with the query result */   mysql_free_result(query_result);   /* close the connection */   mysql_close(db_handle); }
end example



Mastering MySQL 4
Mastering MySQL 4
ISBN: 0782141625
EAN: 2147483647
Year: 2003
Pages: 230
Authors: Ian Gilfillan

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net