0

I am trying to set up the connection with MySQL in Eclipse. I have tried the following -

  1. I have added the "my-sql-connector.jar" to the build path and class path.
  2. I have tried adding it in the WEB-INF.
  3. Tried using class.forName.

After trying all the above, still I am not able to set up the connection. I keep getting the following error -

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/sampledb

Here is my code -

public class Main {

    private static final String USERNAME = "user1";
    private static final String PASSWORD = "user1";
    private static final String CONN_STRING =
            "jdbc:mysql://localhost/sampledb";

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

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
            System.out.println("Connected");
        } catch (SQLException e) {

            System.err.println(e);
        } finally { 
            if (conn != null) {
                conn.close();
            }
        }

I have seen multiple posts on this issue and I have tried all of the suggestions. I am new to Java and trying to get a hands on Java and JDBC, but I am stuck with it for last 2 days. Can someone please guide me with this issue?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
anupam
  • 3
  • 1
  • 3

1 Answers1

2

Did you try registering your Driver? And check if your driver is proper.

Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Enissay
  • 4,969
  • 3
  • 29
  • 56
  • Thanks so much for this. It worked after adding this Class.forName mentioned above. I am not exactly sure what is the issue. But I will be glad if you can explain. – anupam Jan 21 '16 at 02:59
  • @user3571736 Im' just wondering what java version are you using since It's not needed with `Java 6+` !!! Maybe consider updating it ! – Enissay Jan 21 '16 at 03:03
  • `Class.forName` loads the class. More info, check this answer: http://stackoverflow.com/questions/2092659/what-is-the-difference-between-class-forname-and-class-forname-newinstanc – Jaskaranbir Singh Jan 21 '16 at 03:04
  • I know (the link I referenced has this info at end). I am just telling the purpose. – Jaskaranbir Singh Jan 21 '16 at 03:08
  • @Enissay - I am using java7 and that was the exact reason why I didn't add the Class.forName. But looks like I need that. – anupam Jan 21 '16 at 03:08
  • we used java 7 as well, looks like it works with or without the Class.forName, however, after quite few connections, we started getting the same error as No suitable driver. When we included the Class.forName, we never got the error later. Looks crazy though. – user5310198 Jan 22 '16 at 03:29