MySQL JDBC 连接 URL 完整指南
一、前言:JDBC URL 的基本结构
MySQL 的 JDBC 连接 URL 遵循标准格式:
jdbc:mysql://[host][:port]/[database][?property1=value1&property2=value2...]
- :
详细介绍 MySQL JDBC 连接 URL 的标准格式及核心参数。涵盖连接网络、身份认证、会话行为、性能优化、高可用及调试六大类参数详解。提供本地开发、测试及生产环境的推荐配置示例,强调时区设置、SSL 加密、批处理优化等关键点。总结常见陷阱如 autoReconnect 废弃、密码明文风险等,并给出官方文档参考,帮助开发者构建安全高效的数据库连接。
MySQL 的 JDBC 连接 URL 遵循标准格式:
jdbc:mysql://[host][:port]/[database][?property1=value1&property2=value2...]
jdbc:mysql://localhost:3306? 开头,多个参数用 & 分隔✅ 驱动类(Java 8+):
com.mysql.cj.jdbc.Driver
(旧版com.mysql.jdbc.Driver已废弃)
MySQL Connector/J(官方 JDBC 驱动)提供了 100+ 个连接参数。为便于理解和使用,我们按功能分为 6 大类:
| 分类 | 作用 | 关键参数示例 |
|---|---|---|
| 1. 连接与网络 | 控制如何建立和维持数据库连接 | connectTimeout, socketTimeout, useSSL, requireSSL |
| 2. 身份认证与安全 | 用户认证、加密、凭证管理 | user, password, allowPublicKeyRetrieval, defaultAuthenticationPlugin |
| 3. 会话与行为 | 时区、字符集、自动提交等会话属性 | serverTimezone, characterEncoding, useUnicode, autoReconnect |
| 4. 性能与优化 | 查询缓存、批处理、连接池适配 | useServerPrepStmts, cachePrepStmts, rewriteBatchedStatements, useLocalSessionState |
| 5. 高可用与故障转移 | 主从切换、负载均衡、故障恢复 | autoReconnectForPools, loadBalanceStrategy, failOverReadOnly |
| 6. 调试与日志 | 调试信息、慢查询日志、跟踪 | logger, profileSQL, slowQueryThresholdNanos, includeInnodbStatusInDeadlockExceptions |
| 参数 | 默认值 | 说明 | 推荐值 |
|---|---|---|---|
connectTimeout | 0(无限) | 建立 TCP 连接的超时(毫秒) | 5000(5 秒) |
socketTimeout | 0(无限) | 等待服务器响应的超时(毫秒) | 30000(30 秒) |
useSSL | true(8.0+) | 是否使用 SSL 加密连接 | 开发:false;生产:true |
requireSSL | false | 强制要求 SSL(若服务器支持) | 生产环境建议 true |
enabledTLSProtocols | - | 指定 TLS 协议版本 | TLSv1.2,TLSv1.3 |
| 参数 | 默认值 | 说明 | 推荐值 |
|---|---|---|---|
user | - | 数据库用户名 | 必填 |
password | - | 密码 | 必填(或通过 DataSource 设置) |
allowPublicKeyRetrieval | false | 是否允许从服务器获取公钥(用于 caching_sha2_password) | 开发必须设为 true |
defaultAuthenticationPlugin | com.mysql.cj.protocol.a.authentication.Sha256PasswordPlugin | 默认认证插件 | 通常无需修改 |
passwordCharacterEncoding | - | 密码字符编码 | UTF-8(若含中文密码) |
⚠️ 安全警告:
allowPublicKeyRetrieval=true在内网开发环境安全,但生产环境应配合 SSL 使用。密码建议通过连接池配置(如 HikariCP 的dataSource.setPassword()),避免 URL 明文。
| 参数 | 默认值 | 说明 | 推荐值 |
|---|---|---|---|
serverTimezone | 系统时区 | 服务器时区(影响 TIMESTAMP) | Asia/Shanghai(中国) |
characterEncoding | UTF-8 | 客户端字符编码 | UTF-8 |
useUnicode | true | 是否使用 Unicode | true |
autoReconnect | false | 断线自动重连(已废弃) | ❌ 不要使用 |
connectionCollation | - | 连接排序规则 | utf8mb4_unicode_ci |
✅ 关键提示:必须设置
serverTimezone,否则java.time.LocalDateTime可能偏差 8 小时!使用utf8mb4字符集时,确保 URL 不强制为utf8。
| 参数 | 默认值 | 说明 | 推荐值 |
|---|---|---|---|
useServerPrepStmts | false | 使用服务端预编译语句 | true |
cachePrepStmts | false | 缓存预编译语句 | true |
prepStmtCacheSize | 25 | 预编译语句缓存数量 | 250 |
prepStmtCacheSqlLimit | 256 | 单条 SQL 最大长度 | 2048 |
rewriteBatchedStatements | false | 重写批处理为多值 INSERT | true(大幅提升批处理性能) |
useLocalSessionState | false | 本地缓存会话状态(减少查询) | true |
| 参数 | 说明 |
|---|---|
autoReconnectForPools | 专为连接池设计的重连机制(比 autoReconnect 更安全) |
loadBalanceStrategy | 负载均衡策略(如 random, bestResponseTime) |
failOverReadOnly | 故障转移后是否设为只读 |
📌 注意:高可用通常由中间件(如 ProxySQL)或云数据库处理,应用层少用。
| 参数 | 说明 |
|---|---|
logger | 日志实现(如 Slf4JLogger, Jdk14Logger) |
profileSQL | 记录所有 SQL(性能差,仅调试) |
slowQueryThresholdNanos | 慢查询阈值(纳秒) |
includeInnodbStatusInDeadlockExceptions | 死锁异常包含 InnoDB 状态 |
⚠️ 生产环境禁用:
profileSQL=true会严重拖慢性能!
虽然参数顺序不影响功能,但按逻辑分组可提高可读性:
jdbc:mysql://host:port/db?
# 基础连接
connectTimeout=5000&socketTimeout=30000&
# 认证安全
allowPublicKeyRetrieval=true&useSSL=false&
# 会话行为
serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useUnicode=true&
# 性能优化
rewriteBatchedStatements=true&useServerPrepStmts=true&cachePrepStmts=true&prepStmtCacheSize=250&prepStmtCacheSqlLimit=2048
# application-dev.yml (Spring Boot)
spring:
datasource:
url: jdbc:mysql://localhost:3306/auth_center?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useUnicode=true&connectTimeout=5000&socketTimeout=30000&rewriteBatchedStatements=true&useServerPrepStmts=true&cachePrepStmts=true
username: auth_admin
password: 123456
# URL without password in code (set via env var or config server)
spring:
datasource:
url: jdbc:mysql://test-db.insure.com:3306/auth_center?useSSL=true&requireSSL=true&enabledTLSProtocols=TLSv1.2,TLSv1.3&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&useServerPrepStmts=true&cachePrepStmts=true&prepStmtCacheSize=250
# 生产环境 URL(敏感信息通过 K8s Secret 或 Vault 注入)
spring:
datasource:
url: jdbc:mysql://prod-rds.xxx.rds.amazonaws.com:3306/auth_center?useSSL=true&requireSSL=true&verifyServerCertificate=true&allowPublicKeyRetrieval=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&rewriteBatchedStatements=true&useServerPrepStmts=true&cachePrepStmts=true&connectTimeout=3000&socketTimeout=60000
🔒 生产安全要点:启用 SSL 并验证证书,禁用
allowPublicKeyRetrieval,密码不写在 URL 中,超时时间更严格。
// 完整、安全、高性能的 JDBC URL(适用于 Spring Boot 开发)
String url = "jdbc:mysql://localhost:3306/auth_center?"
+ "allowPublicKeyRetrieval=true" // 解决 caching_sha2_password 问题
+ "&useSSL=false" // 本地开发无 SSL
+ "&serverTimezone=Asia/Shanghai" // 避免时间偏差
+ "&characterEncoding=UTF-8" // 字符编码
+ "&useUnicode=true" // 启用 Unicode
+ "&connectTimeout=5000" // 连接超时 5s
+ "&socketTimeout=30000" // 读写超时 30s
+ "&rewriteBatchedStatements=true" // 批处理性能提升
+ "&useServerPrepStmts=true" // 服务端预编译
+ "&cachePrepStmts=true" // 缓存预编译语句
+ "&prepStmtCacheSize=250" // 缓存 250 条
+ "&prepStmtCacheSqlLimit=2048"; // SQL 长度上限 2KB
| 陷阱 | 正确做法 |
|---|---|
不设 serverTimezone | 导致 LocalDateTime 存入偏差 8 小时 → 必须设置 |
| 密码明文写 URL | 使用连接池 API 设置密码(如 HikariCP) |
使用 autoReconnect=true | 已废弃,会导致连接状态不一致 → 改用连接池的健康检查 |
忽略 rewriteBatchedStatements | 批量插入慢 10 倍 → 务必开启 |
生产环境开 allowPublicKeyRetrieval 且无 SSL | 中间人攻击风险 → SSL + 禁用该参数 |
allowPublicKeyRetrieval=true, useSSL=false, 设置时区。useSSL=true, requireSSL=true, 禁用公钥检索,密码外部化。rewriteBatchedStatements + 预编译缓存。serverTimezone 和 characterEncoding。
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online