Java 控制台执行带自定义包定义的类,出现“Exception in thread "main" java.lang.NoClassDefFoundError: ConnectSQLServer (wrong name: sine/ConnectSQLServer)”

时间:2022-07-23 02:44:05

1、先说明一下代码实现:自定义package sine,

源代码保存路径为:E:\JSP\HibernateDemo\HibernateDemoProject\src\sine\ConnectSQLServer.java

 package sine;
import java.sql.*; public class ConnectSQLServer { public static void main(String args[]){
String url="jdbc:sqlserver://localhost:1433;DatabaseName=pubs"; String user_name="sa";
String user_password="sine88";
String sqlStr="select * from jobs;"; try{
Connection con=DriverManager.getConnection(url,user_name,user_password);
System.out.println("Connect Success!");
Statement st=con.createStatement();
System.out.println("Create Statement Success!");
ResultSet rs=st.executeQuery(sqlStr);
System.out.println("Query Success!");
System.out.println("-----------------------"); while(rs.next()){
System.out.println(rs.getString("job_desc"));
}
rs.close();
st.close();
con.close();
}
catch(Exception err){
System.out.println("Connect failed!");
err.printStackTrace(System.out);
}
}
}

2、切换到java源代码所在的文件夹目录下,编译java代码。

E:\JSP\HibernateDemo\HibernateDemoProject\src\sine>javac ConnectSQLServer.java

3、字节码的解释与运行:java ConnectSQLServer 出现如下错误信息:

E:\JSP\HibernateDemo\HibernateDemoProject\src\sine>java ConnectSQLServer
Exception in thread "main" java.lang.NoClassDefFoundError: ConnectSQLServer (wrong name: sine/ConnectSQLServer)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
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)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

4、解决方法

先将控制台上的目录切换到包名的上一个文件夹处,例如,这里的package名称为sine,那么这里就切换到sine的上一层目录,也就是src目录下,

然后执行如下命令:E:\JSP\HibernateDemo\HibernateDemoProject\src>java sine.ConnectSQLServer

此时结果如下:

E:\JSP\HibernateDemo\HibernateDemoProject\src>java sine.ConnectSQLServer
Connect Success!
Create Statement Success!
Query Success!
-----------------------
New Hire - Job not specified
Chief Executive Officer
Business Operations Manager
Chief Financial Officier
Publisher
Managing Editor
Marketing Manager
Public Relations Manager
Acquisitions Manager
Productions Manager
Operations Manager
Editor
Sales Representative
Designer

届时,问题解决! 同理,加入包名是:org.sine,那么执行的时候就需要切换到org的上一个目录下了。