0

I used the following code segment for connecting my java application to mySQL DB, but its giving an error which I can't figure out why.

try {
  con = null;
  String url = "jdbc:mysql://localhost:3306/";
  String db = "ass1";
  String driver = "com.mysql.jdbc.Driver";
  String user = "";
  String pass = "";

  System.out.println("OK 1"); //Checkpoint 1

  Class.forName(driver).newInstance();

  System.out.println("OK 2"); //Checkpoint 2

  con = DriverManager.getConnection(url + db, user, pass);

  System.out.println("OK 3"); //Checkpoint 3
} 
catch (Exception e) {
  System.out.println(e.getMessage());
}

Exception(Output):

run:
OK 1
com.mysql.jdbc.Driver
null
BUILD SUCCESSFUL(total time: 13 seconds)

So the exception is driver itself. It's the first time that I'm encountering this.

P.S.: Please ignore the checkpoints.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • is the driver "com.mysql.jdbc.Driver" in your class path? and no need to call newInstance(),just use Class.forName(driver); – dReAmEr Feb 01 '15 at 06:53
  • 1
    Check for the jar supporting the class has been added or is available in the classpath. I think the jar is mysql-connector.jar – Rohith K Feb 01 '15 at 06:55
  • In addition to below answer Its optional to use`Class.forName()` see http://stackoverflow.com/a/28220350/3841803 – singhakash Feb 01 '15 at 07:12
  • You should really use `printStackTrace()` instead of **only** getting the message. The exception-type itself is important information; most likely you get a `ClassNotFoundException` as you don't have the MySQL JDBC driver on your classpath. – Mark Rotteveel Feb 01 '15 at 08:39
  • That line of code hasn't been needed since 2007. – user207421 Feb 01 '15 at 09:27

2 Answers2

1

No Need to call newInstance() method .

Class.forName(driver);

is enough. Check that the required jar is available in your build path or not ?


Another Suggestion

Always try to use printStackTrace() instaed of getMessage()

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

You do not need to instantiate the driver, just call it's static initialization (e.g., by calling Class.forName) so it gets registered in the DriverManager:

System.out.println("OK 1"); //Checkpoint 1

Class.forName(driver); // no .newInstance() !

System.out.println("OK 2"); //Checkpoint 2

con = DriverManager.getConnection(url + db, user, pass);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 3
    You don't even need to call `Class.forName` since Java 6 (if you have a JDBC 4 compliant driver) as drivers are now loaded using the `ServiceLoader`-mechanism. – Mark Rotteveel Feb 01 '15 at 08:38