这是一个Java连接MySQL的问题,今天有个小老弟问我这个问题,由于很久没写jdbc连接数据库了,我弄了很久才还原了现场。
我用的MySQL驱动版本还挺新的:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
Java程序连接MySQL数据库的方法:
public static Connection getConnection(String url, String user, String password)
我的url:jdbc:mysql://localhost:3306/mytest
时,
报错:
java.sql.SQLException: 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.
java.sql.SQLException:服务器时区值’�й���ʱ��’ 无法识别或代表多个时区。如果要利用时区支持,则必须配置服务器或JDBC驱动程序(通过“ serverTimezone”配置属性)以使用更特定的时区值。
解决方案
- 配置JDBC连接参数
在url连接字符串后面加上?serverTimezone=UTC
例如:
url=jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8&serverTimezone=UTC
关于UTC
UTC
标准时间参照
GMT
格林威治时间
CST
北京时间
我们一般认为GMT和UTC是一样的,都与英国伦敦的本地时相同。
他们之间的关系:
GMT: UTC +0 = GMT: GMT +0
CST: UTC +8 = CST: GMT +8
PST: UTC -8 = PST: GMT -8
如果查询mysql想用北京时间,你得这么写:
url=jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8&serverTimezone=GMT%2B8
- 修改MySQL数据库配置,这个需要用root登录
前提:使用root用户登录mysql
--查看时区值
show variables like '%time_zone%';
--设置为东八区(北京时间)
set global time_zone='+8:00';