0

Hey I am new to java and is right now learning about JDBC. Well i have written this code to create a connection to the sql server where my database is located :

import java.sql.*;
    public class Mysql
    {   
        public static void getmysqlconnection()
        {
            try
            {
                Connection con = null;
                Class.forName("com.mysql,jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost/EMP","root","password");
                System.out.println("connection created");

            }
            catch(SQLException se)
            {
                System.out.println("SQl Exception" + se);


            }
            catch(ClassNotFoundException e)
            {
                System.out.println("ClassNotFoundException" + e);
            }
        }

    public static void main(String args[])
        {
            getmysqlconnection();

        }

}

But on compiling it is generating the following error : ClassNotFoundExceptionjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
saurabh095
  • 29
  • 3
  • Please **NEVER EVER** use `System.out.println(e)` because it will rely on [`Throwable#getLocalizedMessage`](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#getLocalizedMessage--) that doesn't provide enough info of the problem. Please handle your exceptions by at least using `e.printStackTrace()` or use a logger instead. – Luiggi Mendoza Jun 19 '15 at 20:35
  • 1
    Also, when using JDBC 4 driver (MySQL JDBC driver is JDBC 4) **you don't need to use `Class#forName` anymore**, so basically just remove that line and you'll be fine. – Luiggi Mendoza Jun 19 '15 at 20:36
  • Thanks Luiggi your suggestion in exception handling was a gem. But the real problem was that i didn't selected the classpath for my jdbc driver. I had to selecct it because i was using JDBC driver 3. Well i set the classpath from the environment variable and the program worked. But can you tell me the syntax of setting the classpath from cmd? – saurabh095 Jun 23 '15 at 11:04
  • java -cp /path/to/jar:. YourClass – Luiggi Mendoza Jun 23 '15 at 13:37

1 Answers1

2

It seems you have a typo. The class name is com.mysql.jdbc.Driver not com.mysql,jdbc.Driver (dot instead of a comma). Also make sure the MySQL JDBC driver Jar is in the classpath. Otherwise the ClassNotFoundException is thrown.

M A
  • 71,713
  • 13
  • 134
  • 174
  • thamks manouti . I corrected the typo. But the real problem was that i didn't selected the classpath for my jdbc driver. Well i set the classpath from the environment variable and the program worked. But can you tell me the syntax of setting the classpath from cmd? – saurabh095 Jun 23 '15 at 11:07
  • @saurabh095 You typically do `java -cp path_to_jars Main`. See http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html. – M A Jun 23 '15 at 12:11