How do I create a BasicDataSource object?

This example demonstrates how to use the BasicDataSource class of Apache Commons DBCP to create a basic requirements for database connection. The configuration of the data source can be defined using some property method provided by this class. The basic properties are the driver classname, connection url, username and password.

After the datasource ready we can obtain a connection by calling the getConnection() method of the datasource. This method might throw an SQLException when error occurs.

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BasicDataSourceExample {
    public static void main(String[] args) {
        // Creates a BasicDataSource and defines its properties
        // including the driver class name, JDBC url, username
        // and password.
        try (BasicDataSource dataSource = new BasicDataSource()) {
            dataSource.setUrl("jdbc:mysql://localhost/kodejava");
            dataSource.setUsername("kodejava");
            dataSource.setPassword("s3cr*t");

            // Get a connection from the data source and do a
            // database query with the obtained connection.
            try (Connection conn = dataSource.getConnection();
                 PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    System.out.println("Author name: " + rs.getString("author_name"));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

We can simplify the code above so that we don’t have to close the PreparedStatement and Connection manually like we did in the finally block in the code snippet. We can use try-with-resources to automatically close resources. An example can be seen in the following example: How to automatically close resources in JDBC?.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.10.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a database connection pool?

This example shows you how to create a connection pool implementation using the Apache Commons DBCP library.

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConnectionPoolExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    private GenericObjectPool<PoolableConnection> connectionPool = null;

    public static void main(String[] args) throws Exception {
        ConnectionPoolExample demo = new ConnectionPoolExample();
        DataSource dataSource = demo.setUp();
        demo.printStatus();

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
            demo.printStatus();

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println("Author name: " + rs.getString("author_name"));
            }
        }

        demo.printStatus();
    }

    public DataSource setUp() {
        // Creates a connection factory object, which will be used by
        // the pool to create the connection object. We pass the
        // JDBC url info, username and password.
        ConnectionFactory cf = new DriverManagerConnectionFactory(
                ConnectionPoolExample.URL,
                ConnectionPoolExample.USERNAME,
                ConnectionPoolExample.PASSWORD);

        // Creates a PoolableConnectionFactory that will wrap the
        // connection object created by the ConnectionFactory to add
        // object pooling functionality.
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
        pcf.setValidationQuery("SELECT 1");

        // Creates an instance of GenericObjectPool that holds our
        // pool of connection objects.
        GenericObjectPoolConfig<PoolableConnection> config = new GenericObjectPoolConfig<>();
        config.setTestOnBorrow(true);
        config.setMaxTotal(10);
        connectionPool = new GenericObjectPool<>(pcf, config);
        pcf.setPool(connectionPool);

        return new PoolingDataSource<>(connectionPool);
    }

    private GenericObjectPool<PoolableConnection> getConnectionPool() {
        return connectionPool;
    }

    /**
     * Prints connection pool status.
     */
    private void printStatus() {
        System.out.println("Max   : " + getConnectionPool().getNumActive() + "; " +
                "Active: " + getConnectionPool().getNumActive() + "; " +
                "Idle  : " + getConnectionPool().getNumIdle());
    }
}

The code shows the following status as output example:

Max   : 0; Active: 0; Idle  : 0
Max   : 1; Active: 1; Idle  : 0
Author name: Raoul-Gabriel Urma
Author name: Mario Fusco
Author name: Alan Mycroft
Max   : 0; Active: 0; Idle  : 1

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.10.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central