Is there a reason for never closing a JDBC connection?

后端 未结 3 700
独厮守ぢ
独厮守ぢ 2020-12-22 04:22

I\'m reading a code from the last developer that worked on the system and he never closes any connections with the database. He only closes PreparedStatement an

3条回答
  •  悲哀的现实
    2020-12-22 05:12

    He is likely using the same connection to do all SQL processing. That's not a bad technique; but, if he didn't write the code for a clean shutdown, then it can be difficult to know when to close the only connection.

    So I'll wager that this code's rationale is to let the process die, let the socket die as a result of that, and then let the remote database eventually clean up the connection. Does it work, yes. Is is nasty and a place where problems can easily occur, yes.

    The way to fix this is to find your main loop. The one that keeps running. Then you need to control the shutdown by putting the shutdown logic just after the main processing loop. Finally, you'll need to scrub the code of all System.exit(...) calls.

    I'm assuming that since you mentioned the code was inherited, it was Java 1.6 or lower. In the 1.7 and beyond, you can implicitly close a Closeable when using it in the try with resources language construction.

提交回复
热议问题