【问题标题】:Class Notfound exception in sqlserver connection in eclipseeclipse中sql server连接中的Classnotfound异常
【发布时间】:2011-09-16 09:36:04
【问题描述】:

我的 servlet 函数如下所示:

代码:

         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 语句。如何克服这个问题?

尽快回复?

【问题讨论】:

    标签: java sql-server servlets


    【解决方案1】:
    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");
                }
            }
        }
    

    【讨论】:

    • 你的回答与我的问题无关。
    【解决方案2】:

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

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

    【讨论】:

    • 我在 WEB-INF/lib 文件夹中复制了,但在 eclipse 中没有显示。如何克服这个问题?
    • @karthik 您是否尝试过刷新 Eclipse 项目? (右键单击-> 刷新)。然后您可以将该 JAR 文件添加到 Eclipse。
    猜你喜欢
    • 2017-09-22
    • 2011-07-28
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多