How do you use connection pooling with a simple code example?

Connection pooling is a technique used to enhance the performance of executing commands on a database by reusing connections from a pool of established connections. In Java, this can be achieved using libraries like HikariCP, Apache DBCP, or C3P0. Below is a simple example of using HikariCP for connection pooling:

// Import the necessary classes import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.SQLException; public class ConnectionPoolExample { public static void main(String[] args) { // Configure HikariCP HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://localhost:3306/yourDatabase"); config.setUsername("yourUsername"); config.setPassword("yourPassword"); config.setMaximumPoolSize(10); // Set the maximum size of the pool // Create the HikariDataSource HikariDataSource dataSource = new HikariDataSource(config); // Get a connection from the pool try (Connection connection = dataSource.getConnection()) { // Use the connection System.out.println("Connection successful!"); // Perform database operations here } catch (SQLException e) { e.printStackTrace(); } finally { // Close the datasource when done dataSource.close(); } } }

Keywords: Java connection pooling HikariCP database connection JDBC