'How to solve error: java.sql.SQLNonTransientConnectionException: Could not create connection to database server

this is my code

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);

and i encountered this problem java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up. enter image description here



Solution 1:[1]

You are adding up extra with your URL; First you declared this:

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

Now, in the connectToDatabase method you are building the dbURL by putting that URL in between:

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

Your actual dbURL will practically look like: dbURL = "jdbc:mysql://" + "jdbc:mysql://localhost:3306" + ":" + port + "/" + dbName + "?verifyServerCertificate=false";

So, initialize URL just as:

 URL = "localhost";

Solution 2:[2]

I'm just trying to help to resolve the problem with the provided details:). Try,

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);

Note: I didn't set "autoReconnect", "true"

Solution 3:[3]

I was facing the same error. For me it occurred because I was using a very old mysql.connector jar version. Resolved it by upgrading mysql.connector.java jar from mysql:mysql-connector-java:5.4.2 to mysql:mysql-connector-java:8.0.29. In IntelliJ, you can check the version of this jar by navigating to File -> Project Structure -> Libraries -> mysql.connector.java

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shiba
Solution 2 Avishka Dambawinna
Solution 3 Akanksha_p