Sourav
Sourav

Reputation: 17530

Connectivity error Java MySQL

I've installed MySQL Connector J, WAMP [which comes with MySQL], and Java JDK 1.7 but it always through exception com.mysql.jdbc.Driver

The code

import java.sql.*;

public class sou
{
   public static void main (String[] args)
   {
       Connection conn = null;
       try
       {
           String userName = "root";
           String password = "";
           String url = "jdbc:mysql://localhost/cms";
           Class.forName ("com.mysql.jdbc.Driver").newInstance ();
           conn = DriverManager.getConnection (url, userName, password);
            conn.close();
       }
       catch (Exception e)
       {
           System.err.println (e.getMessage());
       }
   }
}

I'm compiling this as

 C:\Users\Sou\Desktop>javac -cp "D:\Program Files\MySQL\Connector J 5.1.20.0\mysql-connector-java-5.1.20-bin.jar" sou.java

Upvotes: 2

Views: 656

Answers (3)

Swapnil
Swapnil

Reputation: 1134

Insert this code in your program to check for classpath System.out.println(System.getProperty("java.class.path"));

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94645

You have to include mysql-connector-java-5.1.20-bin.jar in your CLASSPATH while compiling and running an application.

C:\Users\Sou\Desktop>javac -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
                                    mysql-connector-java-5.1.20-bin.jar" sou.java


C:\Users\Sou\Desktop>java -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
                                    mysql-connector-java-5.1.20-bin.jar" sou

And no need to call the newInstance() method.

   Connection conn = null;
   try{
       String userName = "root";
       String password = "";
       String url = "jdbc:mysql://localhost/cms";
       Class.forName ("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection (url, userName, password);
   }
   catch (Exception e){
       System.err.println (e.getMessage());
   }finally{
       if(conn!=null){
          try{
             conn.close();
          }catch(Exception ex) { }
       }
    }

Upvotes: 3

Alexandre Lavoie
Alexandre Lavoie

Reputation: 8771

You can try this :

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

instead of

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

Upvotes: 0

Related Questions