什么是“if(rs.next())”意思? [英] What does "if (rs.next())" mean?

查看:1452
本文介绍了什么是“if(rs.next())”意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前收到错误,

java.sql.SQLException: Method 'executeQuery(String)' not allowed on prepared statement.

因为我正在使用

PreparedStatement stmt = conn.prepareStatement(sql);

还有

ResultSet rs = stmt.executeQuery(sql);

在我的代码中。

我现在需要删除ResultSet行,但这使我不得不处理以下代码:

I now need to remove the ResultSet line but that leaves me with having to deal with the following code:

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");

我不确定我完全明白什么

I'm not sure I completely understand what

 if (rs.next())

。有人可以向我解释这段代码吗?如果我对此有了更好的理解,我相信我会更好地了解如何使用PreparedStatement结果和rs用于逻辑。此外,对于改变逻辑的任何帮助也将非常感激。

does. Could someone explain this code to me? If I have a better understanding of that I believe I'll have a better idea on how to deal using the PreparedStatement results with the logic being used for rs. Also any help to deal with changing that logic would be greatly appreciated too.

推荐答案

关于<$ c的具体问题$ c> SQLException ,你需要替换

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

因为你正在使用 PreparedStatement 子类而不是声明。使用 PreparedStatement 时,您已经将SQL字符串传递给 Connection#prepareStatement()。您只需在其上设置参数,然后直接调用 executeQuery()方法,而无需重新传递SQL字符串。

because you're using the PreparedStatement subclass instead of Statement. When using PreparedStatement, you've already passed in the SQL string to Connection#prepareStatement(). You just have to set the parameters on it and then call executeQuery() method directly without re-passing the SQL string.

  • JDBC tutorial - Using Prepared Statements

关于 rs.next()的具体问题,它将光标移动到数据库结果集的下一行并返回 true 如果有任何行,否则 false 。结合 if 语句(而不是),这意味着程序员只期望或只对一个人感兴趣第一行。

As to the concrete question about rs.next(), it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that the programmer is expecting or interested in only one row, the first row.

  • Javadoc on ResultSet#next() method
  • Problem with SQL, ResultSet in java

这篇关于什么是“if(rs.next())”意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆