Skip to content

Instantly share code, notes, and snippets.

@lpar
Created June 17, 2011 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpar/1032009 to your computer and use it in GitHub Desktop.
Save lpar/1032009 to your computer and use it in GitHub Desktop.
An example of performing a JDBC query from Java and handling exceptions correctly
/**
* A correct example of performing a SQL query using JDBC.
*
* See http://lpar.ath0.com/2008/09/05/java-jdbc-and-memory-leaks/ for
* discussion; correct examples of Java JDBC code are surprisingly rare.
*/
public static void doSomething() {
try {
Connection connection = DriverManager.getConnection(JDBC_URL);
try {
PreparedStatement statement = connection.prepareStatement("SELECT FIRST,LAST FROM PEOPLE WHERE LAST = ?");
try {
statement.setString(1, "Smith");
statement.execute();
ResultSet results = statement.getResultSet();
try {
while (results.next()) {
String first = results.getString(1);
String last = results.getString(2);
logger.info(first + " " + last);
}
} finally {
results.close();
}
} finally {
statement.close();
}
} finally {
connection.close();
}
} catch (SQLException e) {
logger.severe("Failed to get JDBC connection: " + e.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment