Skip to content

Instantly share code, notes, and snippets.

@tylergannon
Created June 17, 2013 23:21
Show Gist options
  • Select an option

  • Save tylergannon/5801397 to your computer and use it in GitHub Desktop.

Select an option

Save tylergannon/5801397 to your computer and use it in GitHub Desktop.
Managing JDBC resource objects carefully
public class DBHelper {
private static String serverip = "xxx";
private static String database = "xxx";
private static String dbuser = "xxx";
private static String password = "xxx";
public static void closeConnection(Connection connection) {
try { if (connection != null) connection.close(); }
catch (Exception e) {
// Do error stuff
}
}
public static void closeStatement(Statement statement) {
try { if (statement != null) statement.close(); }
catch (Exception e) {
// Do error stuff
}
}
public static void closeResultSet(ResultSet resultSet) {
try { if (resultSet != null) resultSet.close(); }
catch (Exception e) {
// Do error stuff
}
}
public static Connection getConnection() {
return DriverManager.getConnection("jdbc:postgresql://" + serverip + "/" + database, dbuser, password);
}
}
class SomeOtherClass {
public String doSomethingSpecificWithYourDatabase() { // Rather than generalizing
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DBHelper.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(queryString);
// Loop through result set, etc...
return stuff;
} catch(Exception ex) {
// Uh oh, handle errors
} finally {
// Make sure you close everything explicitly, in reverse order of creation.
DBHelper.closeResultSet(resultSet);
DBHelper.closeStatement(statement);
DBHelper.closeConnection(connection);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment