Database Reference
In-Depth Information
If the API program has connected to MySQL, it can query the MySQL server with a query
function suchas mysql_query() . Let's use SELECT to get a list of birds from the
birds table. The code for doing this and displaying the results is as follows:
...
if ( mysql_query ( mysql , "SELECT common_name, scientific_name FROM
birds" )) {
fprintf ( stderr , "%d: %s \n " ,
mysql_errno ( mysql ), mysql_error ( mysql ));
}
else {
result = mysql_store_result ( mysql );
while ( row = mysql_fetch_row ( result )){
printf ( "\%s - \%s \n " , row [ 0 ], row [ 1 ]);
}
mysql_free_result ( result );
}
mysql_close ( mysql );
return 0 ;
}
Within the if statement here, we're using mysql_query() to query MySQL. You
could use the mysql_real_query() functioninstead. It allows the retrieval of binary
data, which can be safer, but isn't necessary for this simple example. The
mysql_query() function returns 0 if it's successful and nonzero if it's not. So if the
SQL statement contained within it doesn't succeed in selecting data from MySQL, an er-
ror message will be printed. However, if the query is successful, the else statement will
then be executed, because the if statement will have received a value of 0.
In the else statement block, the first line usesthe mysql_store_result() function
to store the results of the query in the result variable.
Before letting go of the data, using while , the code loops through each row of the results
set. We're usingthe mysql_fetch_row() function to fetch each row and store it tem-
porarily in the row variable. Because we know how the data is organized from the
SELECT statement, we can use printf with its formatting codes to display each
column. Notice that each column is extracted with standard array syntax (i.e., array
[ n ] ).
Once C has gone through each row of the results, it will stop processing and use
mysql_free_result() to freethe memory for result , concluding the else state-
ment.
Search WWH ::




Custom Search