Mark Lorens
Mark Lorens

Reputation: 83

Java : Failing to connect to mySql DB

I just set up a local mySql database. I can connect to it properly through command line and third party software (Navicat..).

Server: localhost:3306

User: root

Password: password

Database name: students

However, when I try to connect with java, I get an error.

CODE:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Sql {

   public static void main(String[] args) {

    Connection conn = null;

    try {

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

        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students?autoReconnect=true&useSSL=false",
                "root", "password");

        Statement sqlState = conn.createStatement();


    } catch (SQLException ex) {

        System.out.println("SQLException" + ex.getMessage());
        System.out.println("SQLException" + ex.getSQLState());

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

   }

}

OUTPUT:

SQLExceptionCould not create connection to database server. Attempted reconnect 3 times. Giving up.
SQLException08001

Also tried:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students", "root", "password");

and

conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306//students?autoReconnect=true&useSSL=false","root", "password");

Additional Attempts:

The firewall is disabled.

I installed the Jconnector by putting the .bin.jar in:

C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext

I can see it on the left under JRE in Eclipse and the import doesn't give errors.

NOTEs:

Using mySQL from the terminal, workbench or Navicat gives no errors, any query works, the local server is running properly and the credentials are correct, the user has full admin priviledges.

Any suggestions?

Upvotes: 1

Views: 1132

Answers (2)

kyleus
kyleus

Reputation: 1051

I recently had a similar issue. My issue ended up being that the MySQL server version was 8.0.19, while flyway was using a 5.1.40 version of the java MySQL library.

Once I updated the MySQL library version to 8.0.19, my errors went away.

Upvotes: 1

Abhijeet
Abhijeet

Reputation: 4309

This exception can have 4 causes:

  1. User does not have privileges to connect to database.
  2. MySQL service is not running.
  3. Incorrect MySQL-Connector Jar.
  4. Database URL is incorrect;.

Check above prerequisites before connecting to MySQL database.

Upvotes: 0

Related Questions