Queries and Results

Now that you have a physical connection to the database, you can interact with MySQL. The above example used the mysql_query( ) function to get all of the rows from the test table in our sample database:

state = mysql_query(connection, "SELECT test_id, test_val FROM test");

This function returns nonzero on error. Once you send a query, you should therefore check the return code to make sure the query executed properly.

if(state != 0 ) {
    /* Error! */
}

If the return code is 0, you can access any results through the mysql_store_result( ) function:

result = mysql_store_result(connection);

This function returns a pointer to the result set generated by the previous query executed against the specified connection. If that query did not generate results, or if you encounter an error getting to the results, this function returns null. The earlier example does not look for these states—we will go into them in more detail when we cover error handling later in the chapter.

The results given to you by the mysql_store_result( ) function are now under your control. They will exist in memory until you explicitly free them through the mysql_free_result( ) function. In this case, you should step through each row of the results and print the row’s values:

while( (row = mysql_fetch_row(result)) != NULL ) {
    printf("id: %s, val: %s
", (row[0] ? row[0] : "NULL"),
           (row[1] ? row[1] : "NULL"));
}

Even though the test_id column in our database is a numeric column, we still treat it as a null-terminated string in the results. We have to do this since the MYSQL_RES typedef is, in fact, nothing more than an array of null-terminated strings—regardless of their underlying MySQL type. We will perform some more complex result set handling that includes binary data later in this chapter.

Once you are done with the results, you must tell MySQL to free the memory they use:

mysql_free_result(result);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset