0

So I was testing out MySQL databases for the first time, (For the following code, all I want to do is establish a connection to the data base):

import java.sql.*;

public class Driver {

public static void main(String[] args) {

    Connection con = null;
    try{
        String url = "jdbc:mysql://localhost:3306/movie";
        String user = "root";
        String pw = "RockoAndLuke739969";
        con = DriverManager.getConnection(url, user, pw);
    }
    catch(SQLException e){
        e.printStackTrace();
    }
  }
}

And here is the Exception:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/movie at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at Driver.main(Driver.java:13)

And I don't know why it isn't working.... thanks for taking your time to read :) (I am new to stackoverflow by the way, so sorry if I screwed something up xD)

Wyatt Lowery
  • 513
  • 1
  • 7
  • 21

1 Answers1

2

You need to add the driver in your classpath. If you are using maven you have to add the following dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.36</version>
</dependency>

If you aren't using maven check your classpath manually and add the driver to it.

In addition add

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

as first line of your connection code. This line is needed to load the class driver and is used by DriverManager to know wich driver must be used.

Here the reference documentation link

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Thank you so much. I was about to flip when it didn't work xD ( I would vote up your post but I don't have the perms) – Wyatt Lowery Jul 07 '15 at 05:28
  • You can click the up row and green flag. You should have the rights. You haven't rights to up vote your question, not the answers – Davide Lorenzo MARINO Jul 07 '15 at 05:30
  • Oh! Thanks, I really appreciate the quick response :) – Wyatt Lowery Jul 07 '15 at 05:37
  • Using `Class.forName` hasn't been necessary since 2006, with Java 6 (and a JDBC 4 compliant driver), using `.newInstance()` hasn't been necessary since - probably - the start of this century; that was only a workaround for a bug in the MySQL driver. – Mark Rotteveel Jul 07 '15 at 06:31