Friday, 12 September 2014

JDBC DBCP DataSource - MySQL

🚀 Master Java database programming, connection pooling, and MySQL JDBC!

🔔 Subscribe to Ram N Java on YouTube

Why Use Apache Commons DBCP DataSource with MySQL?

Establishing a database connection from scratch for each client request using DriverManager involves expensive network handshakes and authentication. For scalable backend applications, connection pooling is an essential performance optimization.

Apache Commons DBCP provides the BasicDataSource class (implementing javax.sql.DataSource), which pre-allocates and manages a pool of active database connections. Applications borrow a connection to perform SQL operations and return it to the pool upon completion.

Required JAR Dependencies

To implement DBCP connection pooling in your Java project, include the following libraries on your application classpath:

  • commons-dbcp.jar
  • commons-pool.jar
  • mysql-connector-java.jar (MySQL JDBC Driver)

Complete Java Source Code Example

The following Java program configures BasicDataSource for MySQL, borrows a pooled connection, executes a query against the city table in the world database, and iterates through the results:

package com.ram.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;

public class DBCPMySQLDataSourceDemo {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";
    static final String USER = "root";
    static final String PASS = "root";

    // Method to create and configure the BasicDataSource instance
    public static DataSource getDataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(JDBC_DRIVER);
        ds.setUrl(DB_URL);
        ds.setUsername(USER);
        ds.setPassword(PASS);
        return ds;
    }

    public static void main(String[] args) {
        DBCPMySQLDataSourceDemo demo = new DBCPMySQLDataSourceDemo();
        demo.getCityInformation();
    }

    public void getCityInformation() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // Step 1: Obtain configured DataSource
            DataSource dataSource = getDataSource();

            // Step 2: Borrow a connection from the pool
            conn = dataSource.getConnection();

            // Step 3: Create Statement and execute query
            stmt = conn.createStatement();
            String sql = "SELECT ID, Name, CountryCode, District, Population FROM city";
            rs = stmt.executeQuery(sql);

            System.out.println("ID | Name | CountryCode | District | Population");
            System.out.println("-------------------------------------------------");
            while (rs.next()) {
                int id = rs.getInt("ID");
                String name = rs.getString("Name");
                String countryCode = rs.getString("CountryCode");
                String district = rs.getString("District");
                int population = rs.getInt("Population");

                System.out.println(id + " | " + name + " | " + countryCode + " | " + district + " | " + population);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Step 4: Clean up resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close(); // Returns connection to the DBCP pool
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

Key Steps & Best Practices

  • Configure BasicDataSource: Set the driver class name, JDBC URL, username, and password using standard setters on BasicDataSource.
  • Use the DataSource Interface: Assign the configured instance to a standard javax.sql.DataSource variable to keep application code vendor-neutral.
  • Connection Recycling: Calling conn.close() on a pooled connection does not shut down the underlying TCP connection; it returns it back to the pool for reuse.
  • Always close the ResultSet, Statement, and Connection in a finally block to prevent pool starvation.

Related Tutorials You Might Enjoy


Click here to watch in Youtube : https://www.youtube.com/watch?v=ZXGam4BP0DY

Click the below Image to Enlarge
JDBC DBCP DataSource - MySQL

JDBC DBCP DataSource - MySQL
JDBC DBCP DataSource - MySQL

DbcpBasicDataSource.java
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;

public class DbcpBasicDataSource
{

    public static DataSource getDbcpBasicDataSource()
    {

        BasicDataSource basicDataSource = new BasicDataSource();
        try
        {
            basicDataSource.setUrl("jdbc:mysql://localhost:3306/world");
            basicDataSource.setUsername("root");
            basicDataSource.setPassword("root");
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
        return basicDataSource;
    }

    
}
JDBCDataSourceDemo.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

public class JDBCDataSourceDemo
{

    public static void main( String[] args )
    {
        JDBCDataSourceDemo jdbcDataSourceDemo = new JDBCDataSourceDemo();
        jdbcDataSourceDemo.getCityInformation();

    }

    private void getCityInformation()
    {
        Connection connection = null;
        Statement stmt = null;
        /*
         * Get the dbcp2 BasicDataSource
         */
        DataSource dataSource = DbcpBasicDataSource.getDbcpBasicDataSource();
        try
        {
            /*
             *  Get connection from the DataSource
             */
            connection = dataSource.getConnection();
            
            /*
             *  Execute the Query
             */
            
            stmt = connection.createStatement();
            String sql = "select ID,Name,CountryCode,District,Population from city";
            ResultSet rs = stmt.executeQuery(sql);

            /*
             *  Iterate the ResultSet and get each row
             *  Information.
             */
            while( rs.next() )
            {
                /*
                 * Retrieve by column name
                 */
                int id = rs.getInt("ID");
                String name = rs.getString("Name");
                String countryCode = rs.getString("CountryCode");
                String district = rs.getString("District");
                int population = rs.getInt("Population");

                /*
                 * Display values
                 */
                System.out.print("ID: " + id);
                System.out.print(", Name: " + name);
                System.out.print(", CountryCode: " + countryCode);
                System.out.print(", District: " + district);
                System.out.println(", Population: " + population);
            }
            rs.close();     
        }
        catch( SQLException se )
        {
            se.printStackTrace();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if( stmt != null )
                {
                    stmt.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }
            try
            {
                if( connection != null )
                {
                    connection.close();
                }
            }
            catch( SQLException sqlException )
            {
                sqlException.printStackTrace();
            }

        }

    }
}

Output
ID: 2, Name: Qandahar, CountryCode: AFG, District: Qandahar, Population: 237500
ID: 3, Name: Herat, CountryCode: AFG, District: Herat, Population: 100
ID: 4, Name: Mazar-e-Sharif, CountryCode: AFG, District: Balkh, Population: 127800
ID: 5, Name: Amsterdam, CountryCode: NLD, District: Noord-Holland, Population: 50000
ID: 6, Name: Rotterdam, CountryCode: NLD, District: Zuid-Holland, Population: 4000
ID: 7, Name: Haag, CountryCode: NLD, District: Zuid-Holland, Population: 440900
ID: 8, Name: Utrecht, CountryCode: NLD, District: Utrecht, Population: 234323
ID: 9, Name: Eindhoven, CountryCode: NLD, District: Noord-Brabant, Population: 201843
ID: 10, Name: Tilburg, CountryCode: NLD, District: Noord-Brabant, Population: 193238
ID: 11, Name: Groningen, CountryCode: NLD, District: Groningen, Population: 172701

---
---

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCDataSourceDemo-DBCP-Mysql Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCDataSourceDemo-DBCP-Mysql.zip?attredirects=0&d=1

External Links

http://commons.apache.org/proper/commons-dbcp/apidocs/org/apache/commons/dbcp2/BasicDataSource.html

http://commons.apache.org/

http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

http://commons.apache.org/proper/commons-pool/download_pool.cgi

http://commons.apache.org/proper/commons-logging/download_logging.cgi

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials