我不明白的一些行为。 我有一个运行的脚本,如:
ResultSet res = null;
String cmd = new String("SELECT value FROM " +pDS.getValueTableName() + " WHERE itemID=? and propertyID=? ORDER BY checkpointID DESC");
PreparedStatement pstmt= dbconn.prepareStatement(cmd) ;
pstmt.setLong(1,itemID);
pstmt.setLong(2,pDS.getPropertyID());
try {
res = pstmt.executeQuery();
}
catch(Exception e)
{
throw(e);
}
if (!res.next())
{
// other code
}
我在这里得到预期值res.next()=true
。
没有例外。
我想重构代码,并使用try块的Autoclose功能,例如:
ResultSet res = null;
String cmd = new String("SELECT value FROM " +pDS.getValueTableName() + " WHERE itemID=? and propertyID=? ORDER BY checkpointID DESC");
try (PreparedStatement pstmt= dbconn.prepareStatement(cmd) ){
pstmt.setLong(1,itemID);
pstmt.setLong(2,pDS.getPropertyID());
res = pstmt.executeQuery();
}
catch(Exception e)
{
LOGGER.error("Error at getLatestPropertyResultSet",e);
throw(e);
}
if (!res.next())
{
// other code
}
但现在res.next()=false
。结果集itselve是初始化res!=null
。
为什么此修改会改变脚本的行为?
答案 0 :(得分:2)
在没有看到你调用res.next()
的地方的情况下,我只能假设try-with-resource
完全按照宣传的方式进行,并在离开try块后关闭准备好的语句,结果是"关闭& #34;用它。
更新:根据您的修改,我的疑问得到确认。您需要在try块内移动与资源相关的任何工作。