Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...