我正在使用与SQLServer JDBC驱动程序捆绑在一起的示例应用程序。我正在运行Ubuntu 14.10。我在命令行上编译应用程序:
javac -cp .:/path/to/sqljdbc42.jar connectURL.java
并运行它:
java connectURL
这让我很熟悉ClassNotFoundException:
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在运行时仍然会收到抱怨。
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
我在其他地方读过,较新版本的JDBC不需要您通过来加载驱动程序Class.forName,但是如果我删除那行,那么可以预料到java.sql.SQLException: No suitable driver found。
Class.forName
java.sql.SQLException: No suitable driver found
我究竟做错了什么?我确定正在加载.jar并找到了该类,因为如果尝试,例如import com.microsoft.sqlserver.jdbc.SomeNonExistentClass;:
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