java写一个数据库连接池的实现
时间: 2024-04-30 09:25:16 浏览: 95
好的,下面是一个基于 Java 的简单数据库连接池实现:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/myDatabase";
private static final String USER = "root";
private static final String PASSWORD = "password";
private static final int INITIAL_POOL_SIZE = 10;
private static final int MAX_POOL_SIZE = 50;
private List<Connection> connectionPool = new ArrayList<>();
private List<Connection> usedConnections = new ArrayList<>();
public ConnectionPool() {
initializeConnectionPool();
}
private void initializeConnectionPool() {
while (!checkIfConnectionPoolIsFull()) {
connectionPool.add(createNewConnection());
}
}
private synchronized boolean checkIfConnectionPoolIsFull() {
final int MAX_POOL_SIZE = 50;
return connectionPool.size() >= MAX_POOL_SIZE;
}
private Connection createNewConnection() {
Connection connection = null;
try {
Class.forName(DRIVER_CLASS);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException | ClassNotFoundException e) {
System.out.println("Error occurred while creating a new connection: " + e.getMessage());
}
return connection;
}
public synchronized Connection getConnectionFromPool() {
Connection connection = null;
if (connectionPool.size() > 0) {
connection = connectionPool.get(0);
usedConnections.add(connection);
connectionPool.remove(0);
}
return connection;
}
public synchronized void releaseConnection(Connection connection) {
usedConnections.remove(connection);
connectionPool.add(connection);
}
}
```
这个连接池实现的基本思路如下:
1. 使用常量设置数据库的 URL、用户名、密码和连接池的大小(初始大小为 10,最大大小为 50)。
2. 在构造函数中初始化连接池。它使用一个 while 循环来创建新的连接,直到连接池达到最大大小。
3. createNewConnection() 方法创建一个新的数据库连接,如果创建失败,则返回 null。
4. 检查连接池是否已满的 checkIfConnectionPoolIsFull() 方法。
5. getConnectionFromPool() 方法从连接池中取出一个连接。如果连接池为空,则返回 null。
6. releaseConnection() 方法将一个连接放回连接池中。