Description:
When trying to connect to a local MySQL 5.0 server that is not running (its instance has been shutdown), I get some errors (obviously):
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection refused: connect
STACKTRACE:
java.net.ConnectException: Connection refused: connect
[...................................................................]
Etc.
The problem is that I can't see any way to catch that Exception or test if the connection is valid. None of the things I tried work. The manual for Connector/J does not say anything about this.
How to repeat:
Connection con = null;
try{
//Get a connection
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "pass");
} catch(ClassNotFoundException cnfe){
JOptionPane.showMessageDialog(null, "Driver not found", "Driver not found", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch(SQLException se){
JOptionPane.showMessageDialog(null, "SQL Exception", "SQL Exception", JOptionPane.ERROR_MESSAGE);
System.exit(0);
} finally{
try{
//Check if the connection is valid
if(con == null || con.isClosed() || !con.isValid(0)){
JOptionPane.showMessageDialog(null, "Invalid connection", "Invalid connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1;");
} catch(SQLException se){
JOptionPane.showMessageDialog(null, "SQL Exception", "SQL Exception", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
return con;
}
Suggested fix:
The getConnection method should throw the CommunicationsException, or some other Exception maybe.