1

我正在尝试连接 Java 程序,MS SQL SERVER 2012但 Java 抛出exception: java.lang.ClassNotFoundException.

我知道这个问题通常是因为CLASSPATH没有为驱动程序正确设置。我已经按照Oracle的指示添加了一个CLASSPATH,但我仍然遇到同样的异常。当我输入“echo %CLASSPATH%"命令提示符时,我得到了正确的响应。我错过了什么?

代码:

import java.sql.*;
public class JDBCTest {
    public static void main(String[ ] args) throws SQLException {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
        } catch(Exception e) { 
            System.out.println("Can't find database driver: " + e);
        }
    }
}
4

4 回答 4

0

您的应用程序的运行时环境可能不包含适当的 jar 文件。您检查的路径仅适用于您的控制台环境。应用程序类路径与此不同。

于 2012-12-03T09:34:47.837 回答
0

试试这个

 public class connectURL {

        public static void main(String[] args) {

            // Create a variable for the connection string.
String  Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=YourDBName;user=UserName;Password=YourPassword"

            // 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);


                        String SQL = "";
                        stmt = con.createStatement();
                        rs = stmt.executeQuery(SQL);


                        while (rs.next()) {
                            ....
                        }
                }


            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) {}
            }
        }
    }

确保下载驱动程序 jar 文件并将其放在正确的位置

于 2012-12-03T09:38:26.717 回答
0

如果 Class.forName 失败,则是类路径的问题。

试试这个代码来检查你的类路径:

    String classPath = System.getProperty("java.class.path");
    String userDir = System.getProperty("user.dir");
    System.out.println("Working Directory:");
    System.out.println("\t"+userDir);
    System.out.println("Classpath:");
    String[] paths = classPath.split(";");
    for (String path : paths) {
        File pathFile = new File(path);
        String check = pathFile.exists()?"OK        ":"NOT-FOUND ";
        System.out.println("\t"+check+path);
    }
于 2012-12-03T10:04:41.153 回答
0

首先sqljdbc4.jar从下载here

把它.jar放在你的/WEB-INF/lib文件夹中。(如果没有,请检查此文件是否出现在您的 Eclipse 库中,然后刷新您的项目)在此处输入图像描述

然后运行你的项目。

于 2012-12-03T10:06:00.233 回答