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 replaceby
because you’re using the
PreparedStatementsubclass instead ofStatement. When usingPreparedStatement, you’ve already passed in the SQL string toConnection#prepareStatement(). You just have to set the parameters on it and then callexecuteQuery()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 returnstrueif there is any row, otherwisefalse. In combination with theifstatement (instead of thewhile) this means that the programmer is expecting or interested in only one row, the first row.See also:
ResultSet#next()method