我是用在java Web的项目上面的,所以用的是mysql-connect-java-8.0.11版本的jar包。(8.0.12貌似有点问题?)

连接类的与之前有点不同,不然会报找不到类的错误,如下是正确写法:

1
Class.forName("com.mysql.cj.jdbc.Driver");

然后getconnection的参数也多了一点,首先会报如下错误:

1
2
Caused by: 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.

解决方法是在数据库名后面加上serverTimezone=UTC ,如下:

1
("jdbc:mysql://127.0.0.1/cart?serverTimezone=UTC&characterEncoding=utf-8", "root", "root");

然后如果mysql报了如下警告:

1
Establishing SSL connection without server's identity verification is not recommended

说明数据库建立了连接,只是不太安全。我们需要在后面加上一小段代码,最后正确连接如下:

1
("jdbc:mysql://127.0.0.1/cart?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false", "root", "root")