java自定義JDBC實(shí)現(xiàn)連接池
簡單上手
使用 JDBC 來執(zhí)行 SQL 查詢和更新操作
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
System.out.println("成功連接到數(shù)據(jù)庫");
// 查詢操作
String query = "SELECT * FROM your_table_name";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
// 打印查詢結(jié)果
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 更新操作
String update = "UPDATE your_table_name SET name = 'New Name' WHERE id = 1";
int rowsAffected = statement.executeUpdate(update);
System.out.println("更新操作影響的行數(shù): " + rowsAffected);
} catch (SQLException e) {
System.out.println("數(shù)據(jù)庫操作失?。? + e.getMessage());
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("成功關(guān)閉數(shù)據(jù)庫連接");
} catch (SQLException e) {
System.out.println("關(guān)閉數(shù)據(jù)庫連接失?。? + e.getMessage());
}
}
}
}
}
下面展示一些 內(nèi)聯(lián)代碼片。
// A code blockvar foo = 'bar';
// An highlighted blockvar foo = 'bar';
實(shí)現(xiàn)JDBC連接池
JDBC 數(shù)據(jù)庫連接池的示例代碼:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;
public class ConnectionPool {
private static final int MAX_CONNECTIONS = 10; // 最大連接數(shù)限制
private static final long CONNECTION_TIMEOUT = 5000; // 連接超時時間,單位毫秒
private Vector<Connection> availableConnections = new Vector<>();
private Vector<Connection> usedConnections = new Vector<>();
public ConnectionPool(String url, String username, String password) {
initializeConnectionPool(url, username, password);
}
private void initializeConnectionPool(String url, String username, String password) {
while (!checkIfConnectionPoolIsFull()) {
availableConnections.add(createNewConnection(url, username, password));
}
System.out.println("數(shù)據(jù)庫連接池初始化完成,當(dāng)前連接數(shù): " + availableConnections.size());
}
private synchronized boolean checkIfConnectionPoolIsFull() {
return (availableConnections.size() + usedConnections.size()) >= MAX_CONNECTIONS;
}
private Connection createNewConnection(String url, String username, String password) {
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public synchronized Connection getConnection() throws SQLException {
long startTime = System.currentTimeMillis();
while (availableConnections.isEmpty()) {
try {
wait(CONNECTION_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ((System.currentTimeMillis() - startTime) >= CONNECTION_TIMEOUT) {
throw new SQLException("獲取數(shù)據(jù)庫連接超時");
}
}
Connection connection = availableConnections.remove(availableConnections.size() - 1);
usedConnections.add(connection);
System.out.println("獲取數(shù)據(jù)庫連接,當(dāng)前連接數(shù): " + availableConnections.size());
return connection;
}
public synchronized void releaseConnection(Connection connection) {
if (connection != null) {
usedConnections.remove(connection);
availableConnections.add(connection);
notifyAll();
System.out.println("釋放數(shù)據(jù)庫連接,當(dāng)前連接數(shù): " + availableConnections.size());
}
}
}
在上面的示例代碼中,我們增加了最大連接數(shù)限制和連接超時處理機(jī)制。當(dāng)連接池中的連接數(shù)達(dá)到最大值時,新請求會等待一段時間,如果超過連接超時時間仍未獲取到連接,則會拋出 SQLException 異常表示獲取連接超時。同時,我們還通過控制臺輸出連接池的狀態(tài)信息,方便跟蹤連接的獲取和釋放情況。
測試
測試數(shù)據(jù)庫連接池的最大連接數(shù)限制和連接超時處理機(jī)制:
public class ConnectionPoolTest {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";
ConnectionPool connectionPool = new ConnectionPool(url, username, password);
// 模擬多個線程同時請求數(shù)據(jù)庫連接
for (int i = 0; i < 15; i++) {
Thread thread = new Thread(new Worker(connectionPool, i));
thread.start();
}
}
static class Worker implements Runnable {
private ConnectionPool connectionPool;
private int workerId;
public Worker(ConnectionPool connectionPool, int workerId) {
this.connectionPool = connectionPool;
this.workerId = workerId;
}
@Override
public void run() {
try (Connection connection = connectionPool.getConnection()) {
System.out.println("Worker " + workerId + " 獲取到數(shù)據(jù)庫連接");
// 模擬操作持有連接的時間
Thread.sleep(3000);
System.out.println("Worker " + workerId + " 完成操作,釋放數(shù)據(jù)庫連接");
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
關(guān)于SQLException
SQLException 是 Java 中的一個異常類,用于表示與數(shù)據(jù)庫相關(guān)的異常。當(dāng)使用 JDBC 連接數(shù)據(jù)庫時,很多操作都可能會拋出 SQLException 異常,比如連接數(shù)據(jù)庫、執(zhí)行查詢、更新數(shù)據(jù)等過程中出現(xiàn)的錯誤。
SQLException 是 java.sql.SQLException 類的全名,它是 java.sql 包中的一個類,專門用于處理數(shù)據(jù)庫操作可能出現(xiàn)的異常情況。該異常類提供了一系列方法,用于獲取關(guān)于異常的詳細(xì)信息,比如異常消息、SQL 狀態(tài)碼、引起異常的原因等,方便開發(fā)人員進(jìn)行異常處理和調(diào)試。
在使用 JDBC 連接數(shù)據(jù)庫時,通常會在代碼中捕獲 SQLException 異常,并根據(jù)具體情況進(jìn)行異常處理,比如輸出異常信息、回滾事務(wù)、關(guān)閉連接等操作,以確保程序的穩(wěn)定性和可靠性。
下面是一個簡單的示例,演示了如何捕獲并處理 SQLException 異常:
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
// 執(zhí)行數(shù)據(jù)庫操作...
} catch (SQLException e) {
System.out.println("數(shù)據(jù)庫操作失敗:" + e.getMessage());
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("關(guān)閉數(shù)據(jù)庫連接失?。? + e.getMessage());
e.printStackTrace();
}
}
}
}
}
在上面的示例中,我們在連接數(shù)據(jù)庫和關(guān)閉數(shù)據(jù)庫連接的過程中捕獲了 SQLException 異常,并通過 e.getMessage() 方法獲取異常信息進(jìn)行輸出。這樣可以幫助我們更好地理解和處理與數(shù)據(jù)庫交互過程中可能出現(xiàn)的異常情況。
到此這篇關(guān)于java自定義JDBC實(shí)現(xiàn)連接池的文章就介紹到這了,更多相關(guān)java JDBC連接池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Boot?中使用@KafkaListener并發(fā)批量接收消息的完整代碼
kakfa是我們在項(xiàng)目開發(fā)中經(jīng)常使用的消息中間件。由于它的寫性能非常高,因此,經(jīng)常會碰到讀取Kafka消息隊(duì)列時擁堵的情況,這篇文章主要介紹了Spring?Boot?中使用@KafkaListener并發(fā)批量接收消息,需要的朋友可以參考下2023-02-02
Maven編譯錯誤:程序包c(diǎn)om.sun.*包不存在的三種解決方案
J2SE中的類大致可以劃分為以下的各個包:java.*,javax.*,org.*,sun.*,本文文章主要介紹了maven編譯錯誤:程序包c(diǎn)om.sun.xml.internal.ws.spi不存在的解決方案,感興趣的可以了解一下2024-02-02
java數(shù)據(jù)輸出打印流PrintStream和PrintWriter面試精講
這篇文章主要為大家介紹了java數(shù)據(jù)輸出打印流PrintStream和PrintWriter面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
Spring File Storage文件的對象存儲框架基本使用小結(jié)
在開發(fā)過程當(dāng)中,會使用到存文檔、圖片、視頻、音頻等等,這些都會涉及存儲的問題,文件可以直接存服務(wù)器,但需要考慮帶寬和存儲空間,另外一種方式就是使用云存儲,這篇文章主要介紹了Spring File Storage文件的對象存儲框架基本使用小結(jié),需要的朋友可以參考下2024-08-08
解決Weblogic部署war找不到spring配置文件的問題
這篇文章主要介紹了解決Weblogic部署war找不到spring配置文件的問題,具有很好的參考價值,希望對大家有所幫助。2021-07-07
JAVA中跳出當(dāng)前多重嵌套循環(huán)的方法詳解
今天在看面試題時,發(fā)現(xiàn)了這個問題,因?yàn)樵赑HP中跳出多次循環(huán)可以使用break數(shù)字來跳出多層循環(huán),但這在java中并不好使,這篇文章主要給大家介紹了關(guān)于JAVA中跳出當(dāng)前多重嵌套循環(huán)的相關(guān)資料,需要的朋友可以參考下2022-01-01

