Does the connection close in accordance with best practice?

Possible duplicate:
Why would you ever implement finalize ()?

I saw several java files with the following code:

public void finalize() {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
        }
    }
}
  • Does Connectionbest practice cover method finalize?
  • Is it enough to close, Connectionor do I need to close other objects, such as PreparedStatement?
+5
source share
4 answers

From Java 7, the best practice of closing a resource is to use try-with-resource:

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

+8
source

, " " " ". , , , .

, :

try {
  acquire resource
}
finally {
  if (resource was acquired)
    release it
}
+5

, , -. , ,.

/* Acquire resource. */
try {
  /* Use resource. */
}
finally {
  /* Release resource. */
}
+1

Connection , PreparedStatement/Statement/CallableStatement, try, , , conn.

:

 try{

    Connection conn = DriverManager.getConnection(url,username,password);

    PreparedStatement pStat = conn.prepareStatement("Drop table info");

    pStat.executeUpdate();
      }
       catch(Exception ex){
        }

   finally(){

     pStat.close();
     conn.close();
 }
-1

All Articles