java写数据库连接_JAVA写简单的数据库连接池
时间: 2023-07-20 12:28:00 浏览: 103
好的,我可以帮您解答。下面是一个简单的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 DB_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "password";
private static final int MAX_CONNECTIONS = 10;
private List<Connection> connectionPool;
private List<Connection> usedConnections = new ArrayList<>();
private static ConnectionPool instance = new ConnectionPool();
private ConnectionPool() {
connectionPool = new ArrayList<>();
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
return connection;
}
public static ConnectionPool getInstance() {
return instance;
}
public synchronized Connection getConnection() throws SQLException {
if (connectionPool.isEmpty()) {
return createConnection();
} else {
Connection connection = connectionPool.remove(connectionPool.size() - 1);
usedConnections.add(connection);
return connection;
}
}
public synchronized void releaseConnection(Connection connection) {
connectionPool.add(connection);
usedConnections.remove(connection);
}
public int getSize() {
return connectionPool.size() + usedConnections.size();
}
public void closeAllConnections() throws SQLException {
for (Connection connection : connectionPool) {
connection.close();
}
for (Connection connection : usedConnections) {
connection.close();
}
connectionPool.clear();
usedConnections.clear();
}
}
```
该示例代码中,我们使用了Java的线程安全的List来保存空闲连接和已使用连接。在创建连接时,我们使用了Java的JDBC API来获取数据库连接。在获取连接时,我们首先检查连接池中是否有空闲连接。如果没有,则创建新连接。如果有,则从连接池中获取一个连接。在释放连接时,我们将其添加回连接池中。
希望这个示例代码能够帮助您理解如何编写一个简单的Java数据库连接池。
阅读全文