Database Reference
In-Depth Information
Solution
Everyone has problems getting programs to work correctly. But if you don't anticipate
problems by checking for errors, the job becomes much more difficult. Add some error-
checking code so your programs can help you figure out what went wrong.
Discussion
After working through Recipe 2.1 , you know how to connect to the MySQL server. It's
also a good idea to know how to check for errors and how to retrieve specific error
information from the API, so we cover that next. You're probably anxious to do more
interesting things (such as executing statements and getting back the results), but error
checking is fundamentally important. Programs sometimes fail, especially during de‐
velopment, and if you can't determine why failures occur, you're flying blind.
The need to check for errors is not so obvious or widely appreciated as one might hope.
Many messages posted on MySQL-related mailing lists are requests for help with pro‐
grams that fail for reasons unknown to the people who wrote them. Surprisingly often,
people have put in no error checking, thus giving themselves no way to know that there
was a problem or to find out what it was! Plan for failure by checking for errors so that
you can take appropriate action.
When an error occurs, MySQL provides three values:
• A MySQL-specific error number
• A MySQL-specific descriptive text error message
• A five-character SQLSTATE error code defined according to the ANSI and ODBC
standards
The recipes in this section show how to access this information. The example programs
are deliberately designed to fail, so that the error-handling code executes. That's why
they attempt to connect using a username and password of baduser and badpass .
A general debugging aid not specific to any API is to use the avail‐
able logs. Check the MySQL server's query log to see what state‐
ments the server is receiving. (This requires that log to be enabled;
see Recipe 22.3 .) The query log might show that your program is not
constructing the SQL statement string you expect. Similarly, if you
run a script under a web server and it fails, check the web server's
error log.
Search WWH ::




Custom Search