java写一个数据库连接池并且测试
时间: 2023-07-13 18:30:25 浏览: 99
好的,下面是一个使用Java编写的数据库连接池,并测试其连接的示例代码:
```java
import java.sql.Connection;
import java.sql.SQLException;
public class TestConnectionPool {
public static void main(String[] args) throws SQLException {
ConnectionPool connectionPool = ConnectionPool.getInstance();
System.out.println("Initial pool size: " + connectionPool.getSize());
Connection connection1 = connectionPool.getConnection();
System.out.println("Connection 1 obtained, pool size: " + connectionPool.getSize());
Connection connection2 = connectionPool.getConnection();
System.out.println("Connection 2 obtained, pool size: " + connectionPool.getSize());
connectionPool.releaseConnection(connection1);
System.out.println("Connection 1 released, pool size: " + connectionPool.getSize());
Connection connection3 = connectionPool.getConnection();
System.out.println("Connection 3 obtained, pool size: " + connectionPool.getSize());
Connection connection4 = connectionPool.getConnection();
System.out.println("Connection 4 obtained, pool size: " + connectionPool.getSize());
connectionPool.releaseConnection(connection2);
System.out.println("Connection 2 released, pool size: " + connectionPool.getSize());
connectionPool.releaseConnection(connection3);
System.out.println("Connection 3 released, pool size: " + connectionPool.getSize());
connectionPool.releaseConnection(connection4);
System.out.println("Connection 4 released, pool size: " + connectionPool.getSize());
connectionPool.closeAllConnections();
System.out.println("All connections closed, pool size: " + connectionPool.getSize());
}
}
```
在这个示例代码中,我们首先获取连接池的实例,并打印出初始连接池的大小。然后我们获取两个连接,并依次释放它们,并再次获取两个连接。最后,我们关闭所有连接,并打印出连接池的最终大小。
您可以将这个示例代码与前面提供的数据库连接池示例代码结合起来使用。在测试之前,请确保您已经在本地安装了MySQL数据库,并且已经在数据库中创建了一个名为“mydatabase”的数据库。
阅读全文