Handling Errors

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!\nError %u: %s\n", mysql_errno ...

Get Sams Teach Yourself MySQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.