java自定義JDBC實現(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);
// 打印查詢結果
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("成功關閉數(shù)據(jù)庫連接");
} catch (SQLException e) {
System.out.println("關閉數(shù)據(jù)庫連接失?。? + e.getMessage());
}
}
}
}
}
下面展示一些 內(nèi)聯(lián)代碼片。
// A code blockvar foo = 'bar';
// An highlighted blockvar foo = 'bar';
實現(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ù)庫連接池初始化完成,當前連接數(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ù)庫連接,當前連接數(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ù)庫連接,當前連接數(shù): " + availableConnections.size());
}
}
}
在上面的示例代碼中,我們增加了最大連接數(shù)限制和連接超時處理機制。當連接池中的連接數(shù)達到最大值時,新請求會等待一段時間,如果超過連接超時時間仍未獲取到連接,則會拋出 SQLException 異常表示獲取連接超時。同時,我們還通過控制臺輸出連接池的狀態(tài)信息,方便跟蹤連接的獲取和釋放情況。
測試
測試數(shù)據(jù)庫連接池的最大連接數(shù)限制和連接超時處理機制:
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();
}
}
}
}
關于SQLException
SQLException 是 Java 中的一個異常類,用于表示與數(shù)據(jù)庫相關的異常。當使用 JDBC 連接數(shù)據(jù)庫時,很多操作都可能會拋出 SQLException 異常,比如連接數(shù)據(jù)庫、執(zhí)行查詢、更新數(shù)據(jù)等過程中出現(xiàn)的錯誤。
SQLException 是 java.sql.SQLException 類的全名,它是 java.sql 包中的一個類,專門用于處理數(shù)據(jù)庫操作可能出現(xiàn)的異常情況。該異常類提供了一系列方法,用于獲取關于異常的詳細信息,比如異常消息、SQL 狀態(tài)碼、引起異常的原因等,方便開發(fā)人員進行異常處理和調(diào)試。
在使用 JDBC 連接數(shù)據(jù)庫時,通常會在代碼中捕獲 SQLException 異常,并根據(jù)具體情況進行異常處理,比如輸出異常信息、回滾事務、關閉連接等操作,以確保程序的穩(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("關閉數(shù)據(jù)庫連接失?。? + e.getMessage());
e.printStackTrace();
}
}
}
}
}
在上面的示例中,我們在連接數(shù)據(jù)庫和關閉數(shù)據(jù)庫連接的過程中捕獲了 SQLException 異常,并通過 e.getMessage() 方法獲取異常信息進行輸出。這樣可以幫助我們更好地理解和處理與數(shù)據(jù)庫交互過程中可能出現(xiàn)的異常情況。
到此這篇關于java自定義JDBC實現(xiàn)連接池的文章就介紹到這了,更多相關java JDBC連接池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Java實現(xiàn)MapReduce詞頻統(tǒng)計示例代碼
這篇文章主要介紹了使用Java實現(xiàn)MapReduce詞頻統(tǒng)計的相關資料,通過詞頻統(tǒng)計示例來展示MapReduce的運行機制,涵蓋了Mapper和Reducer的實現(xiàn),并說明了如何配置和執(zhí)行MapReduce作業(yè),需要的朋友可以參考下2024-11-11
使用sharding-jdbc實現(xiàn)水平分表的示例代碼
本文主要介紹了sharding-jdbc實現(xiàn)水平分表,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
java使用JNA(Java Native Access)調(diào)用dll的方法
java使用JNA(Java Native Access)調(diào)用windows系統(tǒng)的dll文件的例子2013-11-11

