1

Mycode:

public class database_connection {

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

     Connection conn = null;
      String url = "jdbc:mysql://localhost:3306/";
      String dbName = "mycooldatab";
      String driver = "com.mysql.jdbc.Driver";
      String userName = "root"; 
      String password = "root";  

      try{
          Class.forName(driver).newInstance();// create object of Driver
          conn = DriverManager.getConnection(url+dbName,userName,password);
          // connection will be established

          // *******************Statement******************
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select * from student");

        //  rs.next(); // 1st row
        //  System.out.println(rs.getString("name"));


                }  catch(Exception e){
            e.printStackTrace();
      }finally{
          conn.close();
      }

error : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


I had tried adding the below line to classpath from system environment variables.

"C:\Program Files (x86)\MySQL\Connector J 5.1.20.0\mysql-connector-java-5.1.20-bin.jar"

but still no good. I am getting same error , can someone figure out and suggest solution, please?

Leigh
  • 28,765
  • 10
  • 55
  • 103
MKod
  • 803
  • 5
  • 20
  • 33
  • 1
    problem could be spaces in the system path, put driver in a directory like c:\driver\mysql-driver.jar and give tha in classpath – Subin Sebastian Jan 04 '13 at 02:19
  • it is valid point. though my issue resolved. I think i need to modify my classpath. but the directory is just as it is while installing mysql. i havent done any modifications on directory name. – MKod Jan 04 '13 at 02:24
  • 1
    The classpath currently used depends on how the Java application is executed. E.g. by `java.exe` in command prompt, or as JAR doubleclicked in file explorer, or by *Run* command in an IDE, etc. So, if you elaborate that part in detail, then you will likely get the right answer sooner. – BalusC Jan 04 '13 at 02:42
  • possible duplicate of [ClassNotFoundException: com.mysql.jdbc.Driver](http://stackoverflow.com/questions/8745872/classnotfoundexception-com-mysql-jdbc-driver) - this has been asked hundreds of times already on SO. – Brian Roach Jan 04 '13 at 03:04
  • Setting the system `CLASSPATH` variable almost never works – Mark Rotteveel Jan 04 '13 at 09:06

2 Answers2

2

I doubt your classpath is properly set.

To verify that, add this line at beginning of your main():

 System.out.println("CLASSPATH IS=" + System.getProperty("java.class.path"));

And verify that the mysql-connector-java-5.1.20-bin.jar is properly shown in that line.

Luigi R. Viggiano
  • 8,659
  • 7
  • 53
  • 66
0

sorry, it is mistake from me.

I forgot to add mysql jar file in eclipse that I am using . it is working fine.

MKod
  • 803
  • 5
  • 20
  • 33