在代码上获取ClassNotFoundException:" Class.forName(" com.microsoft.sqlserver.jdbc.SqlServerDriver");" [英] Getting ClassNotFoundException on code: "Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");"
问题描述
这是我的第一个 Java 应用程序,我对 Java 和 NetBeans 完全缺乏经验。
This is my first Java application and I'm completely inexperienced with Java and NetBeans.
我一直在尝试连接到sql并获取一些记录2天。问题是关于 jdbc 驱动程序,让我解释一下。我已经下载了 sqljdbc 驱动程序,然后按照以下步骤操作:
I have been trying to connect to sql and get some records for 2 days. The problem is about jdbc driver, let me explain. I have downloaded sqljdbc driver and then followed these steps:
右键单击Project->选择属性 - >在左侧单击Libraries-> Compile选项卡 - 单击Add Jar / Folder按钮并选择 sqljdbc4.jar 文件。然后它应该没问题,对吧?
Right-click Project->Select Properties->On the left-hand side click Libraries->Under Compile tab - click Add Jar/Folder button and select sqljdbc4.jar file. Then it should be ok, right?
然后我写了这段代码但是我不能摆脱这个例外:
Then I wrote this code But I cant get rid of this exception:
Exception in thread "main" 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:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:30)
这是代码
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:sqlserver://.\\SQLEXPRESS;databaseName=Northwind; Integrated Security = SSPI ";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");
con = DriverManager.getConnection(url);
String sql = "Select Top 3 from * person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
推荐答案
根据这个页面,该类名为 SQLServerDriver
而不是 SqlServerDriver
。案例很重要!
According to this page, the class is called SQLServerDriver
and not SqlServerDriver
. Case is important!
所以,试试:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
请注意,对于较新版本的JDBC,没有必要明确加载驱动程序类使用 Class.forName(...)
。我链接的页面明确说明您不必这样做。所以,你可以删除整行,然后它应该工作。
Note that with newer versions of JDBC, it's not necessary to load the driver class explicitly with Class.forName(...)
. The page I linked to explicitly explains that you don't have to do it. So, you can just remove the whole line and then it should work.
这篇关于在代码上获取ClassNotFoundException:" Class.forName(" com.microsoft.sqlserver.jdbc.SqlServerDriver");"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!