Transaction rollback on SQLException using new try-with-resources block

According to the language spec, the connection will be closed before the catch clause is executed (http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3.2). A possible solution is to nest try-with-resources statements: try (java.sql.Connection con = createConnection()) { con.setAutoCommit(false); try (Statement stm = con.createStatement()) { stm.execute(someQuery); // causes SQLException } catch(SQLException ex) { con.rollback(); con.setAutoCommit(true); throw ex; } con.commit(); con.setAutoCommit(true); } Hopefully … Read more

8 branches for try with resources – jacoco coverage possible?

Well I can’t tell you what the exact problem with Jacoco is, but I can show you how Try With Resources is compiled. Basically, there are a lot of compiler generated switches to handle exceptions thrown at various points. If we take the following code and compile it public static void main(String[] args){ String a … Read more

Close multiple resources with AutoCloseable (try-with-resources)

Try with resources can be used with multiple resources by declaring them all in the parenthesis. See the documentation Relevant code excerpt from the linked documentation: public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with // try-with-resources … Read more

How should I use try-with-resources with JDBC?

I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block. public List<User> getUser(int userId) { try (Connection con = DriverManager.getConnection(myConnectionURL); PreparedStatement ps = createPreparedStatement(con, userId); ResultSet rs = ps.executeQuery()) { // process the resultset here, all resources will be cleaned up } catch (SQLException … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)