【问题标题】:How can I catch "no rows selected" in JSP?如何在 JSP 中捕获“未选择行”?
【发布时间】:2014-08-18 11:14:13
【问题描述】:

我的 JSP 页面包含以下登录验证代码:

<%
 System.out.println("Entered");
 String username=request.getParameter("username");
 String password=request.getParameter("password");
 Connection con=getConnection.getConnectionBuilder();

 PreparedStatement pstmt=con.prepareStatement("Select password from users where username=? and password=?");
 pstmt.setString(1, "username");
 pstmt.setString(2, "password");
 boolean ifTrue=pstmt.execute();
 System.out.println(""+ifTrue);
 if (ifTrue==false)
 {
    out.print("Invalid userid and password combination");
 }
%>

现在的问题是“当我输入无效的用户名和密码组合时,查询从 Oracle 返回 no rows selected,我无法理解如何捕获此消息。我尝试使用布尔值,但正如预期的那样它正在返回true. 我找不到 pstmt 的任何返回字符串和 executeUpdate 返回整数的方法。

【问题讨论】:

  • 您应该使用返回 ResultSet 的 executeQuery() 方法并检查它是否包含任何记录。顺便说一句,在 JSP 中使用这样的代码是非常糟糕的做法......
  • @Zyga,“不好的做法”如何?
  • 除了 Zyga 所说的,您可能还想检查一下您的 if 语句:if (ifTrue=false) 是错误的。 BalusC's excellent answer on this question 包含一些关于为什么不应该在 JSP 中使用 Java 代码的背景信息。
  • 不相关,但是:不要在每次调用 JSP 时创建连接。使用适当的连接池并将您的 JDBC 代码从 JSP 页面移到后端。

标签: java oracle jsp


【解决方案1】:

请尝试以下代码。

PreparedStatement pstmt = con.prepareStatement("Select password from users where username=? and password=?");
pstmt.setString(1, "username");
pstmt.setString(2, "password");
ResultSet resultSet = pstmt.executeQuery();

if(!resultSet.next()) 
    out.print("no rows selected");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多