java if rs.next,什么是“if(rs.next())”意思?

I am currently getting the error,

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

because I am using

PreparedStatement stmt = conn.prepareStatement(sql);

and also had

ResultSet rs = stmt.executeQuery(sql);

in my code.

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())

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.

解决方案

As to the concrete problem with that SQLException, you need to replace

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

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.

See also:

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.

See also:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值