We're nearly ready to put our program together! There's just one more important thing to include: error handling.
Nearly all the API's functions return a value indicating success or failure. If a function fails, you can use mysql_error() and mysql_errno() to report on what went wrong.
For example, we will test the result of mysql_real_connect(). As you saw just now, it returns a MYSQL* connection handle if the connection attempt succeeds, or NULL if it fails. Let's add some error handling to our connection routine, which should now look like this:
if (mysql_real_connect ( mysql, db_host, db_user, db_pass, db_name, db_port, unix_socket, db_flags) == NULL ) { fprintf (stderr, "mysql_real_connect() failed! Error %u: %s ", mysql_errno (mysql), mysql_error (mysql)); return (NULL); }
The functions mysql_error() and mysql_errno() return the error message and error code, respectively, for the most recent API call that could succeed or fail. They take the MYSQL* database connection handle as their argument.
The preceding code example tests the result of mysql_real_connect() and prints an error message if the connection fails together with some error information. For example, a failed connection attempt might generate the following output:
Error 1045: Access denied for user: 'tonyb@localhost' (Using password: YES)
3.145.8.8