Closing Database Connections in Java

前端 未结 6 1363
小鲜肉
小鲜肉 2020-11-22 09:34

I am getting a little confused, I was reading the below from http://en.wikipedia.org/wiki/Java_Database_Connectivity

Connection conn = DriverManager.getConn         


        
6条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 10:12

    It is always better to close the database/resource objects after usage. Better to close connection, resultset and statement objects in the finally block.

    Until Java7, all these resources needs to be closed using a finally block. If you are using Java 7, then for closing the resources you can do as follows.

    try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
    ) {
    
    //statements
    }catch(....){}
    

    Now, con, stmt and rs objects become part of try block and java automatically closes these resources after use.

    Hope I was helpful.

提交回复
热议问题