Database Reference
In-Depth Information
}
catch ( Exception e )
{
e . printStackTrace ();
}
The stack trace shows the location of the problem but not necessarily what the problem
was. Also, it may not be meaningful except to you, the program's developer. To be more
specific, print the error message and code associated with an exception:
• All Exception objects support the getMessage() method. JDBC methods may
throw exceptions using SQLException objects; these are like Exception objects but
also support getErrorCode() and getSQLState() methods. getErrorCode() and
getMessage() return the MySQL-specific error number and message string, and
getSQLState() returns a string containing the SQLSTATE value.
• Some methods generate SQLWarning objects to provide information about nonfatal
warnings. SQLWarning is a subclass of SQLException , but warnings are accumulated
in a list rather than thrown immediately. They don't interrupt your program, and
you can print them at your leisure.
The following example program, Error.java , demonstrates how to access error messages
by printing all the error information available to it. It attempts to connect to the MySQL
server and prints exception information if the attempt fails. Then it executes a statement
and prints exception and warning information if the statement fails:
// Error.java: demonstrate MySQL error handling
import java.sql.* ;
public class Error
{
public static void main ( String [] args )
{
Connection conn = null ;
String url = "jdbc:mysql://localhost/cookbook" ;
String userName = "baduser" ;
String password = "badpass" ;
try
{
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
conn = DriverManager . getConnection ( url , userName , password );
System . out . println ( "Connected" );
tryQuery ( conn ); // issue a query
}
catch ( Exception e )
{
System . err . println ( "Cannot connect to server" );
System . err . println ( e );
Search WWH ::




Custom Search