Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SQL Exception?

 
Chris Cairns
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got the following error and am hoping that someone could explain why.
The error is: java.sql.SQLException: Closed Statement: next.
And it was produced because of the following order of statements:
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read the docs, you need to obtain all the the information from a ResultSet before any of the following can occur:
Close the connection
Close the Statement
Close the ResultSet
Reuse the Statement for another query
Reuse the ResultSet for another query
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris,
A "java.sql.ResultSet" object is _always_ associated with a "java.sql.Statement" object. Therefore, when you close the "Statement", you are effectively also closing the "ResultSet". Hence, as Carl has said, first deal with your "ResultSet" and then youcan close the "Statement".
However, my closing order is the opposite of what Carl has advised. Rather than do this:

Close the connection
Close the Statement
Close the ResultSet

I usually do this:
  • close the "ResultSet"
  • close the "Statement"
  • close the "Connection"

  • Hope this has helped you.
    Good Luck,
    Avi.
     
    Peter den Haan
    author
    Ranch Hand
    Posts: 3252
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Avi Abrami:
    [...] I usually do this:
  • close the "ResultSet"
  • close the "Statement"
  • close the "Connection"

  • In fact, the JDBC specification stipulates that closing a Statement should close all the ResultSets associated with that Statement -- with a fully compliant driver, if you execute the Statement just once and then close it, you shouldn't have to close the ResultSet explicitly.
    Don't think that Connection.close() should close all open Statements, though: if you're using a connection pool that may not happen at all.
    Be pedantic about closing Statements and Connections in finally blocks! Some JDBC drivers will not forgive you for any resource leaks, e.g. the Oracle driver. Even the smallest leak will eventually kill you (you'll run out of cursors).
    - Peter
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic