# java.sql.SQLNonTransientConnectionException：无法连接到地址=(host=<host>)(port=<port>)(type=master)：连接被拒绝

- **ID:** `java/sql-non-transient-connection-exception`
- **领域:** java
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

JDBC驱动程序无法建立到指定数据库主机和端口的TCP连接，通常是因为数据库服务器未运行、端口被防火墙阻止或主机名不可达。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MySQL Connector/J 8.0.33 | active | — | — |
| PostgreSQL JDBC 42.7.1 | active | — | — |
| HikariCP 5.1.0 | active | — | — |

## 解决方案

1. ```
   Verify the database server is running and listening on the expected port. On Linux: `sudo netstat -tulpn | grep <port>`. On Windows: `netstat -ano | findstr :<port>`. If not listening, restart the database service.
   ```
2. ```
   Check firewall rules on both host and network level. Temporarily disable the firewall for testing: `sudo ufw disable` (Linux) or `netsh advfirewall set allprofiles state off` (Windows). Re-enable after testing and add an allow rule for the database port.
   ```
3. ```
   Test connectivity using telnet or nc from the application server: `telnet <host> <port>` or `nc -zv <host> <port>`. If the connection fails, check DNS resolution with `nslookup <host>` and ensure the hostname resolves to the correct IP.
   ```

## 无效尝试

- **Increase connection timeout in JDBC URL (e.g., connectTimeout=60000)** — Timeout only affects how long the driver waits for a response; if the server is down or port is closed, timeout does not help. The connection will still fail after the extended timeout. (95% 失败率)
- **Change the JDBC driver version to an older one** — The error is a network-level issue, not a driver compatibility problem. Changing the driver version does not affect TCP connectivity to the database server. (90% 失败率)
- **Add useSSL=false to the JDBC URL** — SSL configuration is irrelevant when the initial TCP connection cannot be established. The connection refusal happens before any SSL handshake. (85% 失败率)
