如何解决错误:java.sql.SQLNonTransientConnectionException:无法创建与数据库服务器的连接

时间:2020-05-14 16:12:25

标签: java mysql database

这是我的代码

private String dbURL;
private String dbUsername = "root";
private String dbPassword = "root1234";
private String URL = "localhost";
private String port = "3306";
private String dbName = "university";
private Connection con;

private void connectToDataBase() throws ClassNotFoundException, SQLException {

    dbURL = "jdbc:mysql://" + URL + ":" + port + "/" + dbName + "?verifyServerCertificate=false";
    Properties p = new Properties();
    p.setProperty("user", dbUsername);
    p.setProperty("password", dbPassword);
    p.setProperty("useSSL", "false");
    p.setProperty("autoReconnect", "true");
    Class.forName("com.mysql.cj.jdbc.Driver");

    con = DriverManager.getConnection(dbURL, p);

,我遇到了这个问题 java.sql.SQLNonTransientConnectionException:无法创建与数据库服务器的连接。尝试重新连接3次。放弃。 enter image description here

2 个答案:

答案 0 :(得分:0)

您正在添加URL的额外内容; 首先,您声明了这一点:

private String URL = "jdbc:mysql://localhost:3306";

现在,在connectToDatabase方法中,您通过在以下网址之间放置dbURL来构建dbURL:

dbURL = "jdbc:mysql://" + URL + ":" + port + "/" + dbName + "?verifyServerCertificate=false";

您实际的dbURL实际上看起来像: dbURL =“ jdbc:mysql://” +“ jdbc:mysql:// localhost:3306” +“:” +端口+“ /” + dbName +“?verifyServerCertificate = false”;

因此,初始化URL就像:

 URL = "localhost";

答案 1 :(得分:0)

我只是想通过提供的详细信息来帮助解决问题:)。 试试

dbURL = "jdbc:mysql://" + URL + ":" + port + "/" + dbName + "?verifyServerCertificate=false"+ "&useSSL=false";

Properties p = new Properties();
p.setProperty("user", dbUsername);
p.setProperty("password", dbPassword);

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

con = DriverManager.getConnection(dbURL, p);

注意:我没有设置"autoReconnect", "true"