JAVA——[MySQLNonTransientConnectionException:Could not create connection to database server.]解决方案

问题描述

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.

问题分析

使用错误的MySQL驱动。

解决方案

更改JDBC的jar包

更改JDBC驱动名和连接字符串URL 

// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
//static final String DB_URL = "jdbc:mysql://localhost:3306/xxxx";
     
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
//如果MySQL-connector-java用的6.0以上的,则driver要使用:com.mysql.cj.jdbc.Driver
//private static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
//private static String DB_URL = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/xxxx?useSSL=false&serverTimezone=UTC";

注:

url 需要添加时区设置:

serverTimezone=GMT%2B8

(GMT%2B8代表东八区)

也可设置为:serverTimezone=UTC    serverTimezone=Shanghai(会比中国时间早8个小时,如果在中国,可以选择Asia/Shanghai或者Asia/Hongkong)

如果未明确设置,MySQL 5.5.45+, 5.6.26+ and 5.7.6+版本默认要求建立SSL连接。

为了符合当前不使用SSL连接的应用程序,verifyServerCertificate属性设置为’false’。

如果你不需要使用SSL连接,你需要通过设置useSSL=false来显式禁用SSL连接。

如果你需要用SSL连接,就要为服务器证书验证提供信任库,并设置useSSL=true

SSL – Secure Sockets Layer(安全套接层)

Maven

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
            <version>8.0.11</version>
</dependency>

参考文章

https://www.cnblogs.com/xiaoyu666/p/10479636.html

https://www.cnblogs.com/wggj/p/9001899.html

发布了1352 篇原创文章 · 获赞 226 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/weixin_43272781/article/details/103981203