Reputation: 1521
I have been playing around with JDBC drivers. I would like some advice from the experience code masters out there. I was wondering if this is a good way to find if am connected to a database. If it is not, could someone let me know how would they do it?
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/"+database+"?+user="+user+"&password="+password);
} catch (SQLException e) {
System.out.println(e.getMessage());
if (con != null) {
System.out.println("hello");
} else {
System.out.println("Not Connected!");
}
}
I would really appreciate all helpful comments. Many thanks in advance.
Upvotes: 1
Views: 177
Reputation: 122011
If the getConnection
method returns normally, and does not throw an exception, then a connection to the database has been made. The logic within the catch
clause is unrequired, because if an exception is caught a connection was not established.
The returned Connection
object must be close()
d (as many of the JDBC classes must, such as Statement
s and ResultSet
s for example). Assuming Java7, a convenient way to ensure the Connection
is closed is using the try-with-resources statement:
try (Connection con = DriverManager.getConnection(...))
{
}
catch (final SQLException e)
{
}
As stated by SnakeDoc in the comments this may be impractical in production systems because establishing a connection to the database is a typically expensive operation.
Upvotes: 2
Reputation: 12123
The JDBC API will perform these checks for you. Whenever you perform a database operation, such as opening a connection, executing a statement, it will check to see if the connection is valid. If not it will throw an exception.
For example, the method Connection.createStatement throws the following:
SQLException - if a database access error occurs or this method is called on a closed connection
All you have to do is some basic exception handling. Surrounding your JDBC calls with try-catch blocks is one way do this. You could also throw the exception and handle it somewhere else.
Upvotes: 1
Reputation: 244
That's definitely a good way of doing it! If conn can't be initialised it's either your connection string that is wrong or the database is down.
Upvotes: -1