Skip to main content

What is a database connection pool?

·238 words·2 mins
Programming Databases
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and Developer Relations Engineer at MariaDB. He has been programming computers since the mid-90s. Starting with BASIC, Alejandro transitioned to C, C++, and Java during his academic years at the National University of Colombia. He relocated first to the UK and then to Finland to foster his involvement in the open-source industry. Alejandro is a recognized figure in Java and MariaDB circles.

A database connection pool stores ready-to-use database connections that threads can borrow when they need them, and return when they finish the work with the database. This improves performance in terms of memory and processing consumption, especially in web applications such as websites and REST web services. The technique is also known as pooling. Here’s how to use it in Java apps.

HikariCP is one, if not the most, popular JDBC connection pool. You can add it to your project using Maven (check the latest version):

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>LATEST</version>
</dependency>

The connection pool can be configured programmatically or through a configuration file (src/main/resources/database.properties):

jdbcUrl=jdbc:mariadb://localhost:3306/some_database
dataSource.username=the_database_user
dataSource.password=the_password_for_that_user

There are more properties available, like the size of the pool, whether to use auto-commit or not, timeouts, etc. Check the documentation for details.

Now you can create a JDBC DataSource object from which to get Statement or PreparedStatement objects to execute SQL statements:

HikariConfig hikariConfig = new HikariConfig("/database.properties");
HikariDataSource dataSource = new HikariDataSource(hikariConfig);
try (Connection connection = dataSource.getConnection()) {
    // ... run SQL queries here ...
}

If you don’t use a try-with-resources block, remember to return the connection object to the pool by calling connection.close() preferably in a finally block:

try {
    // ... code ...
} finally {
    dataSource.close();
}

See JDBC Tutorial Part 3: Using database connection pools, for a more detailed tutorial or watch me coding an example Java application using Connector/J with a MariaDB database:

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Related

How to execute SQL queries from Java (and prevent SQL injections)
·212 words·1 min
Programming Databases
Instructions on executing SQL queries in Java and preventing SQL injections.
How to open and close JDBC connections
·134 words·1 min
Programming Databases
Guide on opening and closing JDBC connections in Java.
Testing MariaDB ColumnStore performance
·1288 words·7 mins
SQL Databases
A guide to testing the performance of MariaDB ColumnStore.