Skip to content

Commit

Permalink
Testcontainers for Java: Improve implementation of Application.query()
Browse files Browse the repository at this point in the history
Wrap connection into the try-with-resources so that it closes Statement
and result set, and will get closed itself at the end.
  • Loading branch information
amotl committed Apr 6, 2023
1 parent 1846e90 commit 27a1fa4
Showing 1 changed file with 6 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ public void query(String sql) throws IOException, SQLException {
Properties connectionProps = new Properties();
connectionProps.put("user", user);

Connection sqlConnection = DriverManager.getConnection(dsn, connectionProps);
sqlConnection.setAutoCommit(true);
if (sqlConnection.isClosed()) {
throw new IOException("ERROR: Unable to open connection to database");
}
try (Statement stmt = sqlConnection.createStatement()) {
try (Connection sqlConnection = DriverManager.getConnection(dsn, connectionProps)) {
sqlConnection.setAutoCommit(true);
if (sqlConnection.isClosed()) {
throw new IOException("ERROR: Unable to open connection to database");
}
Statement stmt = sqlConnection.createStatement();
boolean checkResults = stmt.execute(sql);
if (checkResults) {
ResultSet rs = stmt.getResultSet();
Expand All @@ -81,7 +81,6 @@ public void query(String sql) throws IOException, SQLException {
throw new IOException("ERROR: Result is empty");
}
}
sqlConnection.close();

}

Expand Down

0 comments on commit 27a1fa4

Please sign in to comment.