mysql-connector-java:8.0连接错误问题
连接com.mysql.jdbc.Driver报错
报错代码:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testmysql","root","123");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
错误描述:加载驱动类错误
Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
是因为用com.mysql.jdbc.Driver 不必要已经被弃用,新驱动类是com.mysql.cj.jdbc.Driver
错误描述:建立连接错误
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 配置属性)
解决方案:
1、mysql-connector包使用的比较新的驱动(5.1版本以上)
jbdc.Driver中的属性值从com.mysql.jdbc.Driver换成com.mysql.cj.jdbc.Driver
2、建立连接增加时区信息问题
增加serTimezone属性并设置时区值,UTC(世界标准时间)和GMT(格林威治时间)都可以。
解决后代码:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testmysql?serverTimezone=GMT","root","123");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}