jab*_*abe 3 java try-catch prepared-statement try-with-resources
在常规Java Try-Catch块中使用PreparedStatements时,我可以更改PreparedStatement以在需要时运行不同的查询,如下所示:
String sqlStatement = "update someTable set someValue = true";
try{
PreparedStatement pstmt = con.prepareStatement(sqlStatement);
pstmt.executeUpdate();
/* Here I change the query */
String anotherSqlStatement = "update aDifferentTable set something = false";
pstmt = con.prepareStatement(anotherSqlStatement);
pstmt.executeUpdate();
}
catch(Exception ex){
...
}
Run Code Online (Sandbox Code Playgroud)
使用Java的Try-with-Resources执行此操作的正确方法是什么?这是我尝试过的,但是"无法分配try-with-resources语句的资源pstmt".
try(Connection con = DriverManager.getConnection(someConnection, user, password);
PreparedStatement pstmt = con.prepareStatement(sqlStatement)){
ResultSet rs = pstmt.executeQuery();
....
/* Here I attempt to change the query, but it breaks */
String anotherSqlStatement = "select something from someTable";
pstmt = con.prepareStatement(anotherSqlStatement);
}
catch(Exception ex){
...
}
Run Code Online (Sandbox Code Playgroud)
我不想再次声明变量,我明白这会破坏Try-with-Resources的目的,我只是想把它分配给别的东西.这样做的正确方法是什么?
考虑一下如果Java允许你这样做会发生什么.如果重新分配pstmt引用的内容,则在第一个PreparedStatement执行后,pstmt将引用第二个PreparedStatement.close方法只在pstmt在块执行完毕时引用的内容上调用,因此在第一个PreparedStatement上永远不会调用close.
而是使用嵌套的try-with-resources块:
try (Connection con = DriverManager.getConnection(someConnection, user, password)) {
try (PreparedStatement pstmt = con.prepareStatement(sqlStatement)) {
pstmt.executeUpdate();
}
try (PreparedStatement pstmt = con.prepareStatement(anotherSqlStatement)) {
pstmt.executeUpdate();
}
}
Run Code Online (Sandbox Code Playgroud)
这样,在不同的范围内有两个pstmt局部变量.第一个PreparedStatement在第二个PreparedStatement开始之前关闭.
| 归档时间: |
|
| 查看次数: |
1306 次 |
| 最近记录: |