【问题标题】:Getting error message as SQLException: No suitable driver found for url获取错误消息为 SQLException:没有为 url 找到合适的驱动程序
【发布时间】:2020-01-20 10:12:28
【问题描述】:

我是 postgresql 数据库的新手。我必须创建一个登录页面,我已经在表中存储了一些用户名和密码。Jar 文件已经添加到类路径中。 这是servlet代码

try
        {
            url2 = getServletContext().getInitParameter("url");
            driver = getServletContext().getInitParameter("name");
            username = getServletContext().getInitParameter("username");
            password = getServletContext().getInitParameter("password");
            Class.forName("org.postgresql.Driver").newInstance();

            Connection connection= DriverManager.getConnection("url","username","password");

            PreparedStatement preparestatement=connection.prepareStatement("SELECT * FROM STORESETUPLOGIN WHERE username=? password=?");        
              preparestatement.setString(1,username);
               preparestatement.setString(2,password);
              ResultSet resultset=preparestatement.executeQuery();         
              status=resultset.next();
             if(status==true) {
                 RequestDispatcher rd=request.getRequestDispatcher("/NewFile.jsp");
                 rd.forward(request,response);
             }
             else{
                 out.print("Oops!!!Sorry username or password error");  
                    RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");  
                    rd.include(request,response);
             }
        }catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e){System.out.println(e);
        e.printStackTrace();
        }   

任何帮助表示赞赏。在此先感谢

【问题讨论】:

  • 不相关,但是:您不应该像那样手动创建连接。在 servlet 容器内配置和使用连接池 (DataSource)。
  • 鉴于错误消息,我会说您的连接 URL 错误 - 但您没有向我们显示您使用的 URL,因此无法回答。
  • 只需在 DriverManager.getConnection() 中将 url 更改为 url2,因为您传递的是硬编码的 url,这就是它显示错误的原因
  • 我是这个数据库的新手,但是我只使用过oracle数据库,所以我不知道在servlet容器中使用连接池。
  • 即使将 url 更改为 url2 后仍然出现错误

标签: java postgresql servlets jdbc


【解决方案1】:

您正在调用 DriverManager.getConnection 并使用纯字符串文字作为参数

    Connection connection= DriverManager.getConnection("url","username","password");

您应该使用在代码示例开头声明的字符串变量

Connection connection = DriverManager.getConnection(url2, username, password);

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多