假设您有以下代码:
Connection conn;
try
{
conn = ... // get connection
conn.setAutoCommit(false);
... // Do some modification queries and logic
conn.commit()
} catch(SQLException e)
{
conn.rollback() // Do we need this?
conn.close()
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,如果有异常,那么关闭连接(因为自动提交已关闭)或显式回滚然后关闭连接是否更好?没有保存点.
我觉得添加回滚调用可能有意义,因为:
1)将来某人可能会添加保存点但忘记添加回滚
2)它提高了可读性
3)它不应该花费任何东西,对吧?
但很明显,这些都不是特别引人注目.任何标准做法?
注意:我知道需要在关闭和回滚时重复try/catch.我实际上有一个中间件,它抽象数据库访问并处理它,但我想知道是否添加它是多余的.
好吧,所以我只是写了一个快速的类,我试图使用try资源而不是try-catch-finally(讨厌做那个)方法,我不断收到错误"非法启动类型".然后我转向它上面的Java教程部分:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html它表明你可以在括号中分配一个新变量.我不确定发生了什么.
private static final class EncryptedWriter {
private final Path filePath;
private FileOutputStream outputStream;
private FileInputStream inputStream;
public EncryptedWriter(Path filePath) {
if (filePath == null) {
this.filePath = Paths.get(EncryptionDriver.RESOURCE_FOLDER.toString(), "Encrypted.dat");
} else {
this.filePath = filePath;
}
}
public void write(byte[] data) {
try (this.outputStream = new FileOutputStream(this.filePath.toFile())){
} catch (FileNotFoundException ex) {
Logger.getLogger(EncryptionDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)