How can you close connections in the Druid connection pool?
When using the Druid connection pool to close connections, you can call the close() method of the connection object to release connection resources. An example is shown below:
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DruidConnectionPoolExample {
public static void main(String[] args) {
// 创建Druid连接池
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("password");
try {
// 获取连接
Connection connection = dataSource.getConnection();
// 执行数据库操作
// ...
// 关闭连接
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接池
dataSource.close();
}
}
}
In the example above, a Druid connection pool object is first created, and a connection is obtained through the getConnection() method. After the database operation is completed, the connection is closed by calling connection.close(), and finally the dataSource.close() is called in the finally block to close the connection pool. This ensures that the connection resources are properly released.