我正在使用MySQL 5.5和mysql-connector-java-5.1.15。(两者都是新安装的)
我使用记事本和命令提示符尝试了JDBC程序。
我的JDBC程序:
import java.sql.*;
import java.io.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "employement";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "12345";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
我在mysql ....中创建了一个名为employement的数据库。
我尝试运行此程序......
C:\Users\Innodea\Desktop>javac MysqlConnect.java
C:\Users\Innodea\Desktop>java MysqlConnect
Exception in thread "main" java.lang.NoClassDefFoundError: MysqlConnect
Caused by: java.lang.ClassNotFoundException: MysqlConnect
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: MysqlConnect. Program will exit.
如何清除此错误?
我也尝试过如下,
C:\Users\Innodea\Desktop>set classpath=C:\Program Files\MySQL\mysql-connector-ja
va-5.1.15\mysql-connector-java-5.1.15.jar
C:\Users\Innodea\Desktop>javac MysqlConnect.java
C:\Users\Innodea\Desktop>java MysqlConnect
Exception in thread "main" java.lang.NoClassDefFoundError: MysqlConnect
Caused by: java.lang.ClassNotFoundException: MysqlConnect
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: MysqlConnect. Program will exit.
同样也会发生同样的错误请帮我清除此错误并运行JDBC程序....
答案 0 :(得分:1)
java -cp .;C:\Program Files\MySQL\mysql-connector-java-5.1.15\mysql-connector-java-5.1.15.jar MysqlConnect
答案 1 :(得分:1)
尝试使用这个 -
java -cp %CLASSPATH%;.; MysqlConnect.java
或者添加。到你的类路径阅读它像
set classpath=C:\Program Files\MySQL\mysql-connector-ja va-5.1.15\mysql-connector-java-5.1.15.jar;.;
你当前的类也需要在classpath上,因此也就是dot-current目录。
答案 2 :(得分:0)
使用-cp开关应该可以正常工作
java -cp=.;C:\Program Files\MySQL\mysql-connector-java-5.1.15\mysql-connector-java-5.1.15.jar MysqlConnect
几乎不需要设置CLASSPATH环境变量