这是一个已经出现的问题before https://stackoverflow.com/questions/3974114/how-can-i-fix-this-package-does-not-exist-error就这样,我确信经验丰富的 Java 开发人员已经厌倦了告诉新手如何设置类路径。也就是说,我尝试通过环境变量和 -cp 选项设置类路径,但没有成功。
我正在使用与 SQLServer JDBC 驱动程序捆绑在一起的示例应用程序。我运行的是 Ubuntu 14.10。我在命令行上编译应用程序:
javac -cp .:/path/to/sqljdbc42.jar connectURL.java
并运行它:
java connectURL
这让我熟悉了ClassNotFoundException
:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at connectURL.main(connectURL.java:42)
我没有修改示例类文件,但为了完整性我将其包含在此处:
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
SQL JDBC .jar 的路径绝对正确。如果我添加import com.microsoft.sqlserver.jdbc.SQLServerDriver;
到类文件我在编译时没有收到任何抱怨,但仍然得到ClassNotFoundException
在运行时。
我在其他地方读到过,较新版本的 JDBC 不需要您通过以下方式加载驱动程序Class.forName
,但如果我删除该行,那么可以预见的是,java.sql.SQLException: No suitable driver found
.
我究竟做错了什么?我确定 .jar 正在加载并且正在找到该类,因为如果我尝试例如import com.microsoft.sqlserver.jdbc.SomeNonExistentClass;
I get:
connectURL.java:2: error: cannot find symbol
我的 Java 详细信息:
$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.10.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)