开发者

JDBC Closing Resources

I am unsure whether a statement and resultset should be closed after each query or after all my queries h开发者_StackOverflow中文版ave been made (ie at the same time i close the connection)?

Correct me if I'm wrong, but I'm pretty sure both work?

However, would the database eventually crash if I didn't close a statement after each query and then performed a lot of queries?

On the other hand, would it be inefficient and time-wasting to keep closing & creating statements for every query?

I've read up a lot on this problem before asking this question, but I'm still uncertain. Any help appreciated,

tre.


From http://www.precisejava.com/javaperf/j2ee/JDBC.htm#JDBC118:

Close ResultSet when finished

Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

In a nutshell, you don't have to explicitly close your ResultSet objects, but it's better to do so to free up memory earlier on. Failing to close your ResultSet objects will just cause the memory that it occupies (which can be small, or large, depending on the size of the result set) to be occupied until the corresponding Statement object is closed.


How much this matters really depends on the specifics of what you're doing. But generally it's better to close a resultset (in a finally block). From everything I've always read and seen, opening the connection itself is where the performance penalties are.

What you don't want to do is open/close connections very quickly (this is why many applications and servers implement connection pooling).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜