2

I'd like to connect to a MySQL database on localhost but i don't know how to make it. I tried this code but it doesn't work:

import java.sql.*;
public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/employee");
            System.out.println("connected");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This error occurs and I don't know if this code is correct or not:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:169)
        at javaapplication1.Main.main(Main.java:28)
roeygol
  • 4,908
  • 9
  • 51
  • 88
Basma Ali
  • 45
  • 7
  • 2
    Have you added the `mysql-connector.jar` in the build path ? – Santhosh Jan 28 '15 at 10:59
  • Please note that XAMPP is just a third-party distribution package which includes MySQL and other things. It isn't a product or a thing you interface Java to. What you are connecting to here is MySQL. – user207421 Jan 28 '15 at 11:06
  • add jdbc driver for mysql on your class path! – faisalbhagat Jan 28 '15 at 11:13
  • Thank you, but i'm a beginner user in java, so could you tell me how can i add the mysql-connector.jar in the build path? – Basma Ali Jan 28 '15 at 12:21

1 Answers1

2

You have to add mysql-connector-java jar file to your project build path or if you use maven add the dependency:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.25</version>
    </dependency>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alist3r
  • 556
  • 3
  • 11
  • 27
  • Thank you, but i'm a beginner user in java, so could you tell me how can i add the mysql-connector-java jar file to my project build path? – Basma Ali Jan 28 '15 at 12:28
  • Download the java connector. Then If u are using Eclipse IDE you have to right-click on your project and click "properties". Then go in "java build path" and click "Add external jar..." and select the downloaded jar. – Alist3r Jan 28 '15 at 12:40