Created
June 17, 2011 18:38
-
-
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
This file contains 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
/** | |
* 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