我目前遇到错误,
java.sql.SQLException: Method 'executeQuery(String)' not allowed on prepared statement.
因为我在用
PreparedStatement stmt = conn.prepareStatement(sql);
也有
ResultSet rs = stmt.executeQuery(sql);
在我的代码中。
我现在需要删除 ResultSet 行,但这让我不得不处理以下代码:
if (rs.next()) {
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("login.successful"));
request.getSession(true).setAttribute("USERNAME", rs.getString("USERNAME"));
request.getSession(true).setAttribute("BALANCE", rs.getString("BALANCE"));
request.setAttribute("msg", "Logged in successfully");
我不确定我完全理解了什么
if (rs.next())
确实如此。有人可以向我解释这段代码吗?如果我对此有更好的理解,我相信我会对如何使用 PreparedStatement 结果和用于 rs 的逻辑有更好的想法。也将不胜感激处理更改该逻辑的任何帮助。
最佳答案
至于那个SQLException
的具体问题,需要替换
ResultSet rs = stmt.executeQuery(sql);
通过
ResultSet rs = stmt.executeQuery();
因为您使用的是 PreparedStatement
子类而不是 Statement
。使用 PreparedStatement
时,您已经将 SQL 字符串传递给 Connection#prepareStatement()
。您只需为其设置参数,然后直接调用 executeQuery()
方法,无需重新传递 SQL 字符串。
另见:
关于rs.next()
的具体问题,将光标移动到数据库结果集的下一行,如果有则返回true
任何行,否则 false
。结合 if
语句(而不是 while
),这意味着程序员只期望或感兴趣一行,即第一行。
另见:
关于java - "if (rs.next())"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8199448/