JDBC:Mysq连接数据库的jar包版本问题(容易掉坑)

1.使用的jar包版本:mysql-connector-5.1.0+

//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/数据库名称", "用户名", "密码");

2.使用的jar包版本:mysql-connector-8.0.0+

如果使用第一种情况的Java代码,会出现以下错误:

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.
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.

出错原因:

1.驱动程序的描述字符串com.mysql.jdbc.Driver是mysql5.0及以前的老写法,而mysql6.0+(包括我用的8.0+)需要这样写com.mysql.cj.jdbc.Driver。

2.MySQL在高版本需要指明是否进行SSL连接和服务器时区(时区必须指明)。解决方案: 在mysql连接字符串url中加入ssl=false(或者true,默认为true)&&serverTimezone=时区。

需要将Java代码更改为:

//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
 //2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/数据库名称?useSSL=false&serverTimezone=服务器时区", "用户名", "密码");
/*
    与5.0+版本的对比:驱动路径变了;多出了useSSL=false&serverTimezone=时区。
    useSSL=false:8.0之前是需要连接数据库是需要建立ssl连接,而8.0之后不需要了,所以需要将其关闭。
    serverTimezone可以填UTC、Asia/Shanghai等等,UTC要比中国时区早8个小时。
*/

注意:Java代码怎么写与jar包的版本有关。

建议:mysql5.0+版本使用mysql-connector-5.0+ jar包,mysql8.0+版本使用mysql-connector-8.0+ jar包。

猜你喜欢

转载自www.cnblogs.com/deng3/p/12752477.html