MySQL JDBC URL时区配置陷阱与正确规避方案
前言
近期在使用MySQL 6.0.x及以上版本的JDBC驱动包时,开发者需要在数据库连接的URL字符串中明确指定serverTimezone参数,否则程序运行时会触发异常报错。
1. 未指定serverTimezone的情况
在XML配置文件中的JDBC URL配置如下:
此时控制台会抛出以下异常信息:
Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
错误提示明确指出:The server time zone value 'йʱ' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.(中文意为:无法识别或代表多个时区的服务器时区值。如果希望使用时区支持功能,必须配置服务器或JDBC驱动程序(通过serverTimezone配置属性)以使用更具体的时区值。)
2. 常见的网络解决方案及其局限
网上许多教程建议直接在URL末尾追加参数?serverTimezone=utc来解决问题。
2.1. 新出现的问题
虽然添加该参数后程序不再抛出连接异常,但在通过Java代码向数据库插入时间数据时,却出现了时间不一致的问题。
例如,在Java代码中准备插入的时间记录为:2026-08-21 17:29:56
然而查询数据库后,发现实际存储的时间变成了:2026-08-21 09:29:56
3. 根本原因分析
这一现象的根本原因在于时区设置的偏差。
UTC(协调世界时)是全球标准时间,而中国使用的是北京时间,即东八区。北京时间比UTC时间快8个小时。
计算公式为:UTC + (+0800) = 本地(北京)时间。当JDBC驱动将UTC时间存入数据库且未进行正确转换或读取时,就会出现上述8小时的时差。
4. 解决方案
应将URL中的时区参数设置为中国标准时间,即serverTimezone=Asia/Shanghai。
4.1 使用Java代码获取本地时区ID
Calendar cal = Calendar.getInstance();
TimeZone timeZone = cal.getTimeZone();
System.out.println(timeZone.getID());
System.out.println(timeZone.getDisplayName());
Asia/Shanghai
中国标准时间
总结
以上就是本文的全部内容,希望这些内容能对各位的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢大家对本站的支持。