# psycopg2.OperationalError: 无法连接到服务器：SSL错误：证书验证失败

- **ID:** `database/ssl-certificate-verify-failed`
- **领域:** database
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

PostgreSQL客户端无法验证服务器的SSL证书，因为CA证书缺失、过期或服务器主机名与证书的CN/SAN不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PostgreSQL 14 | active | — | — |
| PostgreSQL 15 | active | — | — |
| PostgreSQL 16 | active | — | — |
| psycopg2 2.9.9 | active | — | — |
| libpq 15.4 | active | — | — |

## 解决方案

1. ```
   Set the sslrootcert parameter to the correct CA certificate file. Example: sslrootcert=/etc/ssl/certs/ca-certificates.crt in the connection string or ~/.pgpass.
   ```
2. ```
   If the server uses a self-signed certificate, add the server's certificate to the client's trust store. Command: echo 'my_server_cert_pem' >> ~/.postgresql/root.crt && chmod 600 ~/.postgresql/root.crt
   ```
3. ```
   Verify the server hostname matches the certificate's Common Name (CN) or Subject Alternative Name (SAN). Use openssl s_client -connect host:5432 to check the certificate.
   ```

## 无效尝试

- **Disable SSL verification by setting sslmode=disable in the connection string.** — This bypasses security entirely and may violate compliance requirements (e.g., PCI-DSS). It also fails if the server requires SSL. (90% 失败率)
- **Reinstall PostgreSQL server without changing certificate configuration.** — Reinstalling the server does not fix the certificate trust chain; the root cause is the client's CA store or certificate mismatch. (95% 失败率)
