简体   繁体   中英

DBCP Database connections not closing

I am currently creating an application that executes updates on a MySQL database.

I have the following code here:

public int execute(String script, Object... values) throws Exception
{

    Connection con = datasource.getConnection();
    PreparedStatement statement = null;
    int num = 0;

    try{
        try{
            statement = getConnection().prepareStatement(script);

            for (int i = 1; i <= values.length; i++)
            {
                statement.setObject(i, values[i - 1]);
            }

            num = statement.executeUpdate();

        }finally{
            if(statement != null) statement.close();
        }
    }finally{
        if(con != null) con.close();
    }

    return num;

}

After looking at the process list for the database, it is clear the connection is not being closed until the entire data source is closed.

Why isn't the connection being closed?

I'm not entirely sure how your code is structured, but I suspect the issue is you are calling getConnection().prepareStatement(script).

You are getting a connection and assigning it to con, and closing it at the end. However, the statement returned from getConnection()'s Connection is causing that connection to stay open.

You should be calling con.prepareStatement(script)

You are not catching exceptions or handling errors. You should be using Java 7's try-with-resources:

eg

public int execute(String script, Object... values) throws Exception {
    try (Connection con = datasource.getConnection();
            PreparedStatement statment = con.prepareStatement(script)) {

        for (int i = 1; i <= values.length; i++)
        {
            statement.setObject(i, values[i - 1]);
        }

        return statement.executeUpdate();
    } catch (SQLException ex) {
        // handleException
    }
}

This will ensure errors are handled and all resources are correctly closed.

Because it's "borrowed" from pool and "returned" into a pool. Basically, connection pools create well... "pool" of connection's. They spawn multiple connections upon intitialization and increase their number if required and decrease if idle. So when you call close for your current connection, you just release it into a pool while connection itself still remains "alive". All connections are being destroyed if connection pool is being destroyed. Why connection pooling? Because creation of connection upon each request is too expensive.

Here's a good article about connection pooling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM