javamysqlconnectionapache-commons-dbutils

Using DbUtils QueryRunner doesnt close database connections


Im using DbUtils library with QueryRunner class to run my queries. From my underestanding of DbUtils docs I dont need to worry about closing connections. However for some reason it does not close my connections automaticly or even manually. Here is my code:

 public static DataSource createDataSource() {
    BasicDataSource d = new BasicDataSource();
    d.setDriverClassName(Globals.getInstance().getKonfiguracija().dajPostavku("driver"));
    d.setUsername(Globals.getInstance().getKonfiguracija().dajPostavku("dbUsername"));
    d.setPassword(Globals.getInstance().getKonfiguracija().dajPostavku("dbPassword"));
    d.setUrl(Globals.getInstance().getKonfiguracija().dajPostavku("serverDatabase"));
    return d;
}

public static void insertSQL(String sql)
{
    DataSource dataSource = createDataSource();
    QueryRunner qr = new QueryRunner(dataSource);

    try {
        int inserts = qr.update(sql);
        qr.getDataSource().getConnection().close();

    } catch (SQLException ex) {
        Logger.getLogger(DBController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Since im having thread that periodically calls insertSQL method, after some time I get "Too many connections" error. Im using newest version of Tomcat and database is MYSQL.


Solution

  • You're creating a new DataSource on every call to the insertSQL() method: this is probably the cause of the exception.

    Instead, you should create the DataSource once, and then pass the instance to the QueryRunner constructor, for example:

    QueryRunner queryRunner = new QueryRunner(dataSource);
    

    Using a DataSource, you normally don't need to manually close the connection.

    See https://commons.apache.org/proper/commons-dbutils/examples.html for more examples.