2016-05-30 7 views
0

いくつかの動作はわかりません。ここで私は期待値res.next()=trueを取得PreparedStatementがtryブロックのリソースとして使用されている場合、異なる結果が発生する

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 
} 

: は、私のような実行中のスクリプトを持っています。 例外はスローされません。

私は、コードをリファクタリングしたい、とのように、tryブロックの自動クローズのfuntionaltyを使用します。しかし、今

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を。結果セットは初期化されましたres!=null

この変更により、スクリプトの動作が変更されたのはなぜですか?

+1

ここで 'res.next()'を呼び出していますか? – shmosel

+0

この情報を追加しました。私の質問を定式化した後、私は今根本的な疑いがある。 'try {}'ブロックの後に 'pstmt.close()'が呼び出され、さらに 'res.close()'が返されます。 – BerndGit

+0

'try(ResultSet res = stmt.executeQuery()){...}' 。 –

答えて

2

res.next()に電話をしていないと、私はtry-with-resourceが広告された通りに正確にやっているとしか思えず、tryブロックを離れると準備された文を閉じることができます。

更新:あなたの編集に基づく疑いが確認されました。リソースに関連する作業をtryブロック内に移動する必要があります。

+0

さて、わかりました。ご確認、ありがとうございます。私はprogammingでres.close()が呼び出されたことに気づいていませんでした。 – BerndGit

関連する問題