eclipse中sqlserver连接中的类Notfound异常

时间:2011-06-16 13:40:49

标签: java sql-server servlets

我的servlet功能如下所示:

CODE:

         protected void doGet(HttpServletRequest request, HttpServletResponse response)       throws ServletException, IOException {
     // TODO Auto-generated method stub
        response.setContentType("text/html");
        String userName;
        String passwd;
        Connection conn = null;

        userName = (String)request.getParameter("userName");
        passwd = (String)request.getParameter("password");
        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //Or any other driver

        }
        catch( Exception x ){
                System.out.println( "Couldn’t load drivers!" ); 
        }
        try
        {
            conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test","sample","sample");
        }
        catch( Exception x)
        {
            System.out.println("Couldnot get connection");
        }
    }

输出转到两个catch语句。如何克服这个问题?

尽快回复?

2 个答案:

答案 0 :(得分:1)

您是否在Eclipse中运行此操作?看起来您需要将驱动程序JAR文件添加到依赖项中。您可以从Eclipse中的项目构建路径设置执行此操作(右键单击项目,选择“构建路径” - >“配置构建路径”)。然后在“库”选项卡下,您可以添加所需的任何jar,例如SQL Server驱动程序JAR文件。

如果要将其部署到Servlet容器,看起来WEB-INF/lib文件夹中缺少JAR文件。将它复制到这里,您应该会发现它有效。

答案 1 :(得分:0)

try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test", "sample", "sample");
    } catch (ClassNotFoundException e) {
        System.out.println( "Couldn’t load drivers!" );
    } catch (SQLException e) {
        System.out.println("Couldnot get connection");
    }

try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection("jdbc:sqlserver://192.168.0.123:1433;databaseName=test", "sample", "sample");
    } catch (Exception e) {
        if (e instanceof ClassNotFoundException) {
             System.out.println( "Couldn’t load drivers!" );
        } else {
            if (e instanceof SQLException) {
                System.out.println("Couldnot get connection");
            }
        }
    }