Created
June 17, 2013 23:21
-
-
Save tylergannon/5801397 to your computer and use it in GitHub Desktop.
Managing JDBC resource objects carefully
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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