What does "if (rs.next())" mean?

Turk picture Turk · Nov 20, 2011 · Viewed 99k times · Source

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.

Answer

BalusC picture BalusC · Nov 20, 2011

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: