Druid Connection Pool Setup Guide
The Druid connection pool is an open-source, high-performance connection pool used for managing database connections. Here is how to use the Druid connection pool:
1. Include the Druid connection pool dependency: In the project’s build file, such as the Maven pom.xml file, add the dependency for the Druid connection pool.
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
2. Set up the Druid connection pool: Include the necessary parameters for the Druid connection pool in the project’s configuration file, such as application.properties or application.yml, including the database URL, username, and password.
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3. Create a Druid connection pool object: Create a Druid connection pool object in the code and set the relevant parameters for the connection pool.
import com.alibaba.druid.pool.DruidDataSource;
...
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("root");
dataSource.setPassword("123456");
4. Get Database Connection: Acquire a database connection from the Druid connection pool to carry out SQL operations.
import java.sql.Connection;
import java.sql.SQLException;
...
Connection connection = dataSource.getConnection();
Perform SQL operations: use the obtained database connection to execute SQL operations, such as queries, inserts, updates, etc.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
...
Statement statement = connection.createStatement();
String sql = "SELECT * FROM my_table";
ResultSet resultSet = statement.executeQuery(sql);
// 处理查询结果...
...
resultSet.close();
statement.close();
6. Close the database connection: After using the database connection, it is necessary to manually close the connection in order to free up resources.
connection.close();
By following the above steps, you can use the Druid connection pool to manage database connections, thus enhancing the performance and efficiency of database operations.