Release database resources in Java

zhaozj2021-02-11  223

Will Statement and ResultSet on the Connection?

The closing of the cascaded closure seems to be very reasonable, and in many places are also correct, usually write connection con = getConnection (); // getConnection is your methodPrepRepareStatement PS = Con.PrePareStatement (SQL); ResultSet RS = Ps.executeQuery (); ... /// rs.close (); /// ps.close (); con.close (); // no! This is that the connection is an interface, its Close implementation It is a variety of diversified. In normal case, you use DriverManager.getConnection () to get a Connection instance, calling its Close method to close Statement and ResultSet. But in many cases, you need to use the database connection pool. When you call the CONNECTION in the connection pool, the Connection may not be released, but returns to the connection pool. It may be taken out by other code. If you do not release Statement and ResultSet, STATEMENT and RESULTSET that are not closed on Connection may be more and more, then ... On the contrary, I have seen this, someone shuts it off, but continue to use ResultSet, think so Yes, it has triggered a fierce discussion. If you don't have to say more?

So we must release the database resources very carefully. The following code snippet shows this process.

Connection con = NULL; preparedStatement ps = null; ResultSet RS = NULL;

Try {con = getConnection (); // getConnection is your method ps = con?preparestatement (SQL); RS = ps.executeQuery (); ///........... }catch (SQLException EX ) {/// error handling} finally {try {if (ps! = Null) ps.close ();} catch (sqlexception ex) {/// error handling} Try {if (con! = Null) conif.close ();} Catch (SQLEXCEPTION EX) {/// Error handling}}

Very trouble is? But in order to write a robust program, these processing is necessary.

转载请注明原文地址:https://www.9cbs.com/read-5147.html

New Post(0)