连接及关闭数据库时区错误提示:The server time zone value '???ú±ê×??±??' is unrecognized or represents more than one

配置环境:JDK1.8

mysql:5.7.22

mysql connector:mysql-connector-java-8.0.15

错误提示: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.

解决这个错误有以下的三种方法(推荐使用方法一):

方法一:

出现这个错误的原因是因为新版的Mysql中的时区默认设置与本地时区之间是不同的,因此会报错。由此,解决方法即为修改时区设置即可,可以在连接数据库的url的最后添加这样一段代码?serverTimezone=UTC,把时区设置成协调世界时UTC;或者加入代码:?serverTimezone=GMT%2B8&useSSL=false,把GMT时间加上8个小时就等于东八区的时间;就可以解决问题了。JDBC执行数据库插入操作显示乱码情况,参照我的另一篇博客:JDBC执行数据库插入操作中文显示乱码。

https://blog.csdn.net/Tszching_Leung/article/details/88366607

如,我原先的代码为:

//定义mysql数据库的连接地址
public static final String DBURL=“jdbc:mysql://localhost:3306/mldn”;
修改后的代码:

//定义mysql数据库的连接地址
public static final String DBURL=“jdbc:mysql://localhost:3306/mldn?serverTimezone=UTC”;
运行结果:

方法二:

修改MySql系统时区

mysql命令行输入:show variables like “%time_zone%”;#查看当前mysql时区设置

mysql命令行输入:

set global time_zone = ‘+8:00’; #修改mysql全局时区为北京时间,即我们所在的东8区

set time_zone = ‘+8:00’; #修改当前会话时区

flush privileges; #立即生效

方法三:

修改mysql目录下的my.ini配置文件,添加

default-time_zone = ‘+8:00’

然后重启mysql即可。

最后贴上完整的Java代码供参考:

package sqltest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDemo02 {

//定义mysql的数据库驱动程序
public static final String DBDRIVER="com.mysql.cj.jdbc.Driver";
//定义mysql数据库的连接地址
public static final String DBURL="jdbc:mysql://localhost:3306/mldn?serverTimezone=UTC";
//数据库的连接用户名
public static final String DBUSER="root";
//mysql数据库的连接密码
public static final String DBPASS="123456";
public static void main(String[] args) {
	Connection conn=null;//数据库连接
	try{
		Class.forName(DBDRIVER);//加载驱动程序
	}catch(ClassNotFoundException e){
		e.printStackTrace();
	}
	try{
		//连接mysql数据库时,要写上连接的用户名和密码
		conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
	}catch(SQLException e){
		e.printStackTrace();
	}
	System.out.println(conn);
	try{
		conn.close();//关闭数据库
	}catch(SQLException e){
		e.printStackTrace();
	}
}

}

作者:睡觉也能赚钱
来源:CSDN
原文:https://blog.csdn.net/tszching_leung/article/details/88360280
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(连接及关闭数据库时区错误提示:The server time zone value '???ú±ê×??±??' is unrecognized or represents more than one)