我正在使用Windows 8上的MySQL Connector J在Java和MySQL之间进行简单连接。
以下是我尝试执行的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Version {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "testuser";
String password = "test623";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
编译: javac Version.java(没有错误并生成类文件)
执行: java -cp“mysql连接器java jar文件的路径”版本
执行结果:
Exception in thread "main" java.lang.NoClassDefFoundError: Version
Caused by: java.lang.ClassNotFoundException: Version
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Version. Program will exit.
知道我哪里错了吗?
答案 0 :(得分:3)
您必须将包含Version.class的目录添加到类路径以及mysql-connector-jar。
如果没有向invokation添加classpath参数,java将默认在当前目录中查找class-files。如果你添加一个类路径,java将只 搜索提到的jar文件/目录中的类文件,当前目录必须明确包含在.