How to Handle Connection Pooling in JDBC in Java?
Last Updated :
15 May, 2024
In Java applications, interacting with the databases using JDBC (Java Database Connectivity), and managing the database connections efficiently is crucial for optimal performance and resource utilization. Connection pooling is the technique employed to achieve the goal by reusing the established database connections instead of creating new ones for each request.
JDBC usage is establishing the new database connection involving the costly network communication process, authentication, and resource allocation. This can significantly impact application performance, especially in the interactions of frequent databases. When an application needs to perform database operations, it will be requested to the connection from the pool, utilized it and it will be returned it to the pool once it is done. This approach can minimize the overhead of the connection establishment and teardown, leading to be improved performance and scalability.
Prerequisites:
The Following are the Prerequisites to Handle Connection Pooling in JDBC in Java
- Database Setup
- JDBC Driver (Java Database Connectivity Driver)
- Connection Pooling Library
- Java Development Environment
- Project Configuration
Steps to Handle Connection Pooling in JDBC
Step 1: Create a Table in Your Database
- Create a table in your database (Example: Employee).
Here is the basic example of an employee table:

Step 2: Set Up Project in Eclipse IDE
- Open Eclipse IDE. Create one Java project and name it as JDBCWithHikariCP.
- Add HikariCP Dependency to the Java project.
- Create two Class files in a Java project and name it as ConnectionManager and Main respectively.
Here is the path for Class files in Java project:
Path for Class filesStep 3: Implement the Code
Open ConnnectionManager.java file and replace with the below code.
Java
import java.sql.Connection;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class ConnectionManager {
private static final HikariDataSource dataSource;
static {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3307/work");
config.setUsername("root");
config.setPassword("tiger");
// Set maximum pool size
config.setMaximumPoolSize(10);
// Other configuration options
dataSource = new HikariDataSource(config);
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void close() {
if (dataSource != null) {
dataSource.close();
}
}
}
Explanation of the above Program:
- Import the classes/interfaces for the JDBC and HikariCP configuration.
- Manage the database connection using the HikariCP connection pooling.
- Once the class is loaded into the memory, it will be execute.
- Configures HikariCP DataSource with the connection parameters such as JDBC URL, username, passwords and maximum pool size.
- Retrieves a database connection from connection pool with the help of getConnection() Method.
- If a connection can't be obtained, it will throws the SQLException.
- Closes the connection with close() method.
- To avoid the NullPointerException, checks if the dataSource is not null before closing.
Note: Make sure that you can replace JDBC URL, username and password.
Step 4: Use ConnectionManager in Main Class
Open Main.java file and replace with the below code:
Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Get connection from ConnectionManager
connection = ConnectionManager.getConnection();
if (connection != null) {
// Prepare statement
String sql = "SELECT * FROM employees";
preparedStatement = connection.prepareStatement(sql);
// Execute query
resultSet = preparedStatement.executeQuery();
// Process and print results
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} else {
System.out.println("Failed to get connection.");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close(); // Return connection to pool
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the connection pool when application exits
ConnectionManager.close();
}
}
Explanation of the above Program:
- In main class, program starts the execution.
- We can declare the three variables i.e. connection, preparedstatement, resultSet .Here, connection is used to establish the connection to the database. preparedstatement s used to execute the SQL queries. resultSet is used to stores the results returned by database query.
- We are use the try-catch block to handle the potential errors that will be occur during the database operations.
- We are get the database connection from ConnectionManager class. Make sure it is properly configured.
- If you are getting the connection successfully, we can prepare an SQL statement for retrieve data from database table employees.
- We are execute SQL query and store the results in resultSet.
- We loop through resultSet to retrieve the each row data such as ID and name and it prints in the console window.
- If any errors are occurred in the above steps SQLException will be catch the exception and prints the message in the console window.
- Make sure that database resources are properly closed in the finally block to avoid the risks.
- After finish the program, we can close the connection pool which is managed by the ConnectionManager.
Step 5: Run the Code
- After complete the implementation of code, you need to run the code.
- For run the code, right click on the project the Run As > Java Application.
Here is the Output shown below in your console window:
OutputNote:
- If you get "Failed to get connection", it means application is failed to establish a connection to the database.
- You need to check the following troubleshoot the issues:
- Verify Database URL
- Check Database Credentials
- Database Server Running
- Firewall and Network Issues
- Database Driver
- Database Configuration
- Error Logging
Similar Reads
How to handle connection leaks in JDBC? In this article, we will learn how to handle connection leaks in JDBC. Handling connection leaks in JDBC involves ensuring that database connections are properly closed after they are no longer needed. The connection leaks occur when a connection is opened but not closed. Due to connection leaks, th
4 min read
How to Implement Connection Timeout with HikariCP in JDBC? HikariCP is a lightweight, high-performance JDBC connection pooling library that provides fast and efficient management of database connections for Java applications. In this article, we are going to implement a connection timeout with HikariCP. HikariCP LibraryLet's ensure that we have the HikariCP
3 min read
How to Handle SQLException in JDBC? Java Database Connectivity (JDBC) serves as the backbone for Java applications when interacting with databases. While establishing connections and executing queries, we developers often encounter SQLExceptions, which are inevitable in the real world. Handling those exceptions is crucial in the devel
4 min read
How to Handle Large Data Transfers Efficiently in Java Networking? Handling large data transfers efficiently in Java networking plays a main role for the Java applications that need to transfer significant amounts of data over the network connection while maintaining performance and reliability. Optimizing the data transfer is essential for building the file sharin
5 min read
Setting Up Proxy Connection to a System in Java In today's networking environments, categorically corporate ones, application developers have to deal with proxies virtually as often as system administrators. In some cases the application should utilize the system default settings, in other cases, it will be additive to have very tight control ove
7 min read
Java Program to Insert Details in a Table using JDBC Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgres, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data). Algorithm: Search/ Insert/ D
4 min read
How to Connect to a Database Using JDBC with SSL/TLS? Connecting to a database using JDBC with SSL/TLS is nothing but it will Setup a secure connection between the Java program(from IDE, for Example: Eclipse) and the database server, and it will ensure that transferring the data between the Java program and database server is protected. Connecting to t
3 min read
How to Implement a Simple Chat Application Using Sockets in Java? In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment). Java sockets can be connection-oriented or connection-less. In Java, we
4 min read
Java JDBC Programs - Basic to Advanced This article provides a variety of programs on JDBC, that are frequently asked in the technical round in various Software Engineering/JAVA Backend Developer Interviews including various operations such as CREATE, INSERT, UPDATE, DELETE and SELECT on SQL Database etc. Additionally, all programs come
3 min read