我想连接到localhost上的MySQL数据库,但我不知道如何制作它。我试过这段代码,但它不起作用:
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();
}
}
}
发生此错误,我不知道此代码是否正确:
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)
答案 0 :(得分:2)
您必须将mysql-connector-java jar文件添加到项目构建路径中,或者如果您使用maven添加依赖项:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>