com.microsoft.sqlserver.jdbc.SQLServerDriver的ClassNotFoundException

这是SO 之前出现的一个问题,我确信经验丰富的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; 我明白了:

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) 

你在那里一半。 编译时在类路径中包含JDBC JAR,但是在执行时也需要将它包含在类路径中:

 java -cp。:/ path / to / sqljdbc42.jar connectURL