2016-05-13 6 views
1

、私は必要なときにそうように、別のクエリを実行するPreparedStatementを変更することができます。Try-with-ResourcesでPreparedStatementを2回使用するにはどうすればよいですか?通常のJava try-catchブロックでのPreparedStatementを使用する場合

はしてみてください-Javaのを使用して、これを行うための正しい方法は何ですか
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){ 
    ... 
} 

- リソース? これは私が試したことですが、 "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){ 
    ... 
} 

、私はそれは私がちょうど何か他のものにそれを割り当てたい、試してみてください - と - リソースの目的を台無しにしてしまう理解しています。それを行う正しい方法は何ですか?

+2

これは重複しているかどうかわかりません。この質問は、割り当てをしようとするものです。彼は複数のリソースを試しています。 – chrylis

+0

より一般的には、意味的に異なる目的のために変数を再使用しないでください。それは混乱し、バグを導入する良い方法です。不変性はあなたの友人です。 – AjahnCharles

答えて

3

Javaがこれを可能にするとどうなるか考えてみましょう。 pstmtが参照するものを再割り当てすると、最初のPreparedStatementが実行された後、pstmtは2番目のPreparedStatementを参照します。 closeメソッドは、ブロックの実行が終了した時点でpstmtが参照するものにのみ呼び出されるため、closeは最初のPreparedStatementでは呼び出されません。

代わりに、ネストされたのtry-と、リソースブロックを作る:

try (Connection con = DriverManager.getConnection(someConnection, user, password)) { 
    try (PreparedStatement pstmt = con.prepareStatement(sqlStatement)) { 
     pstmt.executeUpdate(); 
    } 

    try (PreparedStatement pstmt = con.prepareStatement(anotherSqlStatement)) { 
     pstmt.executeUpdate();    
    } 
} 

この方法を異なるスコープで2てpstmtのローカル変数があります。最初のPreparedStatementは、2番目のPreparedStatementが開始する前に閉じられます。

+0

質問の2番目の例では、ResultSetを使用しています。try-with-resources句(AutoCloseableでもあります)にその値を含めることを忘れないでください。 @ネイサン私はあなたがあなたの例でそれを見せたいのかどうか分かりません。 – AjahnCharles

関連する問題