When is ResultSet closed?

后端 未结 3 412
旧巷少年郎
旧巷少年郎 2020-11-30 13:33

I want to know if ResultSet can be closed if I didn\'t close it ? I have a ResultSet is closed exception but I am sure I didn\'t close the ResultSet anywhere . What I do exa

相关标签:
3条回答
  • 2020-11-30 13:50

    In case you have closed any of the following, your ResultSet will be closed automatically:

    1. Statement object.
    2. Connection object.

    I am strongly suspecting the connection is being closed. It is a natural tendency to close the database connection once the query is run. While it is a good practice, but may be you are closing the connection even before you have used the ResultSet object inside your TableModel class.

    0 讨论(0)
  • 2020-11-30 13:56

    Directly from the docs on ResultSet.close():

    Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

    ...

    Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.

    So, if you closed the Statement that generated your ResultSet is closed, you get that exception.

    Another question's answer: you shouldn't read results from a ResultSet like that. Perform the select an read all the data you need from the ResultSet at once, close the connection and then later you can read the fetched data as much as you want. You really shouldn't have an external resource/class calling your getValueAt method, which you expect to still be connected to the database. Connection may be terminated for many other reasons, so that's not the way to go.

    Third answer: answered above.

    Last answer: releasing resources explicitly, without waiting for it to be closed when Statement is.

    0 讨论(0)
  • 2020-11-30 13:59

    I always close Connections, ResultSets and Statements in finally {} block. In such case I don't have this problem, since this block is always executed (Well, not always, but here it fits). Please refer to this post, I placed skeleton implementation that might be interesting for you.

    0 讨论(0)
提交回复
热议问题