早期專案使用 Oracle 8i 時常遇 ORA-12500 等連接數耗盡錯誤,團隊編寫 JDBC 壓測工具驗證資料庫連接上限。現轉用 MySQL,同樣需要一個輕量級程式快速測試 max_connections 設定是否生效。本文提供可直接編譯執行的完整範例。
import java.sql.*;
import java.io.IOException;
public class TestMySQLMaxConnections {
public static void main(String[] args) {
final int MAX_ATTEMPTS = 1000; // 陣列上限,防 OOM
Connection[] conns = new Connection[MAX_ATTEMPTS];
Statement[] stmts = new Statement[MAX_ATTEMPTS];
ResultSet[] rss = new ResultSet[MAX_ATTEMPTS];
int successCount = 0;
try {
// 1. 載入驅動 (MySQL 5.1+ 可省略 Class.forName,保留相容舊版)
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
// 2. 迴圈建立連接,直到拋出 SQLException
for (int i = 0; i < MAX_ATTEMPTS; i++) {
conns[i] = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql?useSSL=false&serverTimezone=UTC",
"root", "your_password"
);
stmts[i] = conns[i].createStatement();
rss[i] = stmts[i].executeQuery("SELECT 1"); // 輕量查詢驗證連接可用
rss[i].next();
System.out.print(i + " ");
successCount++;
}
} catch (SQLException e) {
System.out.println("\n連接失敗:" + e.getMessage()
+ " (錯誤碼:" + e.getErrorCode() + ", SQLState: " + e.getSQLState() + ")");
} catch (Exception e) {
System.out.println("\n其他異常:" + e);
} finally {
// 3. 釋放資源並等待用戶確認
System.out.println("\n成功建立 " + successCount + " 個連接。按 Enter 關閉...");
try { System.in.read(); } catch (IOException ignored) {}
for (int i = successCount - 1; i >= 0; i--) {
closeQuietly(rss[i]);
closeQuietly(stmts[i]);
closeQuietly(conns[i]);
System.out.print(i + " ");
}
System.out.println("\n所有連接已關閉。");
}
}
private static void closeQuietly(AutoCloseable resource) {
if (resource != null) {
try { resource.close(); } catch (Exception ignored) {}
}
}
}
com.mysql.cj.jdbc.Driver;5.1 版用 com.mysql.jdbc.Driver。建議依賴管理工具 (Maven/Gradle) 引入對應版本 mysql-connector-j。useSSL=false 避免本地測試 SSL 握手失敗;serverTimezone=UTC 解決時區警告。SELECT 1 比 SELECT * FROM user 更快、無權限依賴。finally 區塊配合 closeQuietly 確保不因單一關閉失敗導致後續資源洩漏。MAX_ATTEMPTS 防止 JVM Heap 耗盡先於資料庫拒絕連接。SHOW VARIABLES LIKE 'max_connections';SET GLOBAL max_connections = 500; (需 SUPER 權限,重啟失效)my.cnf / my.ini 的 [mysqld] 區段 max_connections=500 並重啟服務。| 錯誤碼 | SQLState | 含義 |
|---|---|---|
| 1040 | 08004 | Too many connections (達 max_connections) |
| 1042 | 08S01 | Unable to connect to host (網路/主機/埠不可達) |
| 1045 | 28000 | Access denied (帳密錯誤) |