0

I am trying to do a simple link to a database but every time I try to run it it gives me a "no suitable driver error". I am following a tutorial so I'm unsure as to why mine is not working compared to the shown example.


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

public class google {

    private static final String USERNAME = "Johns";
    private static final String PASSWORD = "done11";
    private static final String CONNECTOR = "jdbc:mysql://localhost/grading";

    public static void main(String[] args) throws SQLException {

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(CONNECTOR, USERNAME, PASSWORD);
            System.out.print("connected");
        } catch (SQLException e) {
            System.err.print(e);
        }

        finally {
            if (conn != null) {
                conn.close();
            }
        }

    }

}

the ecpected output is for it to say "connected", but the error it gives is "java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/grading"

  • 1
    Possible duplicate of [Connect Java to a MySQL database](https://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database) – bhusak Oct 08 '19 at 03:34

1 Answers1

0

declare driver before creating connection

Class.forName("com.mysql.jdbc.Driver")
conn = DriverManager.getConnection(CONNECTOR, USERNAME, PASSWORD);
Mesar ali
  • 1,832
  • 2
  • 16
  • 18
  • i added that and it gives a '''Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type ClassNotFoundException''' –  Oct 08 '19 at 03:36
  • you need to add driver jar file dependency to your project, you can download from official mysql website here https://dev.mysql.com/downloads/connector/j/ – Mesar ali Oct 08 '19 at 03:38
  • ive done that now. but it gives me a communications link error. it says "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server." –  Oct 08 '19 at 03:57
  • check if your mysql server running `mysql -p -ujohns` – Mesar ali Oct 08 '19 at 03:58
  • Using `Class.forName()` hasn't been necessary for ages (I think since Java 1.6) –  Oct 08 '19 at 05:52