Home > Blockchain >  result set doesn't close correctly
result set doesn't close correctly

Time:11-20

I need to do some operation and I have this code:

ResultSet rsSel = null;
// preparated statemen
PreparedStatement stmtSel = null;
// preparated statemen
PreparedStatement stmtUpd = null;
try {
  //create query yyyyyyyy
  String query = SQLStatements.getStatement("queryExample");

  //create PreparedStatement
  stmtSel = (PreparedStatement) conn.prepareStatement(query);

  int index = 1;
  // WHERE:
  stmtSel.setInt(index  , prog);
                                    
  // SELECT:
  rsSel = stmtSel.executeQuery(); //the problem is here
  rsSel.next();  
  //close finally          
  rsSel.close()

and in my finally I do:

finally{
  close(stmtSel);
close(rsSel);
}

               

I don't know why when the programs does rsSel = stmtSel.executeQuery(); it gives me :

Closing a result set you left open! Please close it yourself.: java.lang.Throwable: STACKTRACE

Anyone can help me?

CodePudding user response:

The error is caused by too wide scopes, a hidden exception maybe or some quirk in the control flow. Best is to use try-with-resources which also closes on return/break/exception. Then you would have:

String query = SQLStatements.getStatement("queryExample");
try (PreparedStatement stmtSel = conn.prepareStatement(query)) {
    int index = 1;
    stmtSel.setInt(index  , prog);
    ...
    try (ResultSet rsSel = stmtSel.executeQuery()) {
        if (rsSel.next()) {
            ...
        }
    } // Closes rsSel
} // Closes stmtSel

The cast to PreparedStatement is not needed, assuming you import the java.sql.PreparedStatement.


By the way:

Indentation in java was with the introduction as per convention set to 4. One wanted "less deep nesting of statements." An indentation of 2 I now have in a Delphi Pascal project. Conventions in java are well upheld.

CodePudding user response:

Close rssel first and then stmtsel

try{
   ......
} finally{
   close(rsSel);
   close(stmtSel);
}
  • Related