、私は必要なときにそうように、別のクエリを実行する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){
...
}
、私はそれは私がちょうど何か他のものにそれを割り当てたい、試してみてください - と - リソースの目的を台無しにしてしまう理解しています。それを行う正しい方法は何ですか?
これは重複しているかどうかわかりません。この質問は、割り当てをしようとするものです。彼は複数のリソースを試しています。 – chrylis
より一般的には、意味的に異なる目的のために変数を再使用しないでください。それは混乱し、バグを導入する良い方法です。不変性はあなたの友人です。 – AjahnCharles