问题
I am a newbie in java and I'm developing a Java EE application on the Netbeans 6.9.1 IDE. I have to connect my java application with SQL Server 2005.
For that I have downloaded the sqljdbc.jar file and have put it into C:\Program Files (x86)\Microsoft SQL Server\JDBC Drver\lib
on my system and have set its classpath on command prompt like this
set classpath=.;C:\Program Files (x86)\Microsoft SQL Server\JDBC Drver\lib\sqljdbc.jar
and have set the classpath in the IDE by right clicking on the main project and selecting its property selecting libraries. Then in compile tab added a sqljdbc.jar
, but when I execute this code
import java.sql.*;
/**
*
* @author abc
*/
public class DBConnection
{
public Connection dbConnect(String db_connect_string)
{
try
{
Class.forName(
"com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn =
DriverManager.getConnection(db_connect_string);
System.out.println("connected");
return conn;
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
return null;
}
}
}
it is giving me ClassNotFound error on this line Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
回答1:
You need to check the JDBC driver documentation which came along with your SQL server version. In the old SQL Server 2000, the JDBC driver class name is like as you have:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
However, since SQL Server 2005, Microsoft changed the JDBC driver class name:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Fix it accordingly.
Please note that the CLASSPATH
environment variable is ignored by Netbeans and all other decent Java programs. Forget about it and don't even try to set it until you understand why it exists and what it is to be used for.
回答2:
Can you try:
set classpath=.;"C:\Program Files (x86)\Microsoft SQL Server\JDBC Drver\lib\sqljdbc.jar"
If this does not, try replacing folders with spaces in their names with short name. To get short names, try
dir /-n
回答3:
If you use Maven, you can try adding following to pom.xml:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
来源:https://stackoverflow.com/questions/8458788/classnotfoundexception-in-loading-jdbc-driver