在常规的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){
...
}
如何使用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){
...
}
我不想再次声明变量,我知道这会失去Try-with-Resources的意义,我只想把它赋值给其他变量。该怎么做呢?