-1

I am getting a weird exception when I run the code.

public MySQL()
    {

        Connection conn = null;
        String userName = "admin";
        String password = "admin";

        try
        {
            Class.forName("com.mysql.jdbc.driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testbase",userName,password);
            System.out.println("CONNECTED");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("Can't connect to database!");
        }
    }

All I am getting is this exception.

java.lang.ClassNotFoundException: com.mysql.jdbc.driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
Can't connect to database!  at com.baze.gimnazija.MySQL.<init>(MySQL.java:15)
    at com.baze.gimnazija.Main.main(Main.java:9)

I have the library connected.

1 Answers1

3

The issue is here:

Class.forName("com.mysql.jdbc.driver");

That's not the name of the class. Java is case sensitive, so you must respect the capital letters.

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

If you use Mysql 8, then the driver class has changed:

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

Note: if you're using Java 7 or superior, you can omit that line of code.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332