Connecting SQL Server in JAVA using Eclipse, Error: ClassNotFoundException

Connecting SQL Server in JAVA using Eclipse, Error: ClassNotFoundException

目标是使用 Java 连接到 MS SQL 服务器数据库并执行一些 SQL 语句。 查找 class 时出现问题,错误:java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

尝试了 classname com.microsoft.jdbc.sqlserver.SQLServerDrivercom.microsoft.sqlserver.jdbc.SQLServerDriver

Eclipse 中的类路径也设置为:

CLASSPATH C:/Program Files/Microsoft JDBC Driver 4.1 for SQL Server/sqljdbc_4.1/enu/sqljdbc.jar

还将win7环境变量更改为:

.;C:\Program Files\Microsoft JDBC Driver 4.1 for SQL Server\sqljdbc_4.1\enu\sqljdbc.jar;C:\Program Files\Microsoft JDBC Driver 4.1 for SQL Server\sqljdbc_4.1\enu\sqljdbc4.jar;C:\Program Files\Microsoft JDBC Driver 4.1 for SQL Server\sqljdbc_4.1\enu\sqljdbc41.jar;

使用此代码:

package edu.umt.oop.lecture7;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class databasepro {

    public static void main(String[] args)
      {
        Connection connection = null;
        try
        {
          // the sql server driver string
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

          // the sql server url
          String url = "jdbc:microsoft:sqlserver://C-LHE-CS-68541:1433;DatabaseName=CMSA_Console";

          // get the sql server database connection
          connection = DriverManager.getConnection(url,"sa", "123456");


          System.out.println("\nSuccess");
          // now do whatever you want to do with the connection
          // ...

        }
        catch (ClassNotFoundException e)
        {
          e.printStackTrace();
          System.exit(1);
        }
        catch (SQLException e)
        {
          e.printStackTrace();
          System.exit(2);
        }
      }


}

抛出的完整错误是:

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
    at java.net.URLClassLoader.run(Unknown Source)
    at java.net.URLClassLoader.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at edu.umt.oop.lecture7.databasepro.main(databasepro.java:15)

这是由于 jar 文件。因此,从 link 下面下载 jar 文件并将其下载到 IDE 中的项目库,例如蚀.

Download Jar