java 使用 PreparedStatement 执行 sql 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11815012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:27:36  来源:igfitidea点击:

sql query execute with PreparedStatement

javasqlservletsprepared-statementexecutequery

提问by URL87

I have the follow code in a servlet -

我在 servlet 中有以下代码 -

            String loginID = request.getParameter("loginId").toString();
            String loginPassword = request.getParameter("loginPassword").toString();
            String strSQLcount = "SELECT COUNT(*) as 'Number Of Match' "
                + "FROM persons " + "WHERE (password =? AND  id =?);";
            PreparedStatement prepareSQL = connection
                    .prepareStatement(strSQLcount);
            prepareSQL.setString(1, loginPassword);
            prepareSQL.setString(2, loginID);
            ResultSet numOfMatchResult = prepareSQL.executeQuery();
            // now we know number of matchs ...
            int numOfMatch = numOfMatchResult.getInt(1);

When on running and reach to the line int numOfMatch = numOfMatchResult.getInt(1);it throws the exception - java.sql.SQLException. I checked it and seen that it because the executeQuery()retrieved no one . it occur although I have in personstable ,created with MySQL, the 2 fields - id (text)with value "300" and password (text)with value "500" . and of course I check it when loginIDand loginPasswordwith same 2 values . I checked all the other things about the connection to the DB and it was OK .. so I think the problem is in the SQL syntax in strSQLcount.

在运行并到达该行时,int numOfMatch = numOfMatchResult.getInt(1);它会引发异常 - java.sql.SQLException。我检查了一下,看到它是因为executeQuery()没有检索到任何人。尽管我在persons用 MySQL 创建的表中有 2 个字段 -id (text)值“300”和password (text)值“500” , 但它还是会发生。当然我检查时loginID,并loginPassword用同样的2倍的值。我检查了有关与数据库连接的所有其他内容,一切正常.. 所以我认为问题出在strSQLcount.

采纳答案by JB Nizet

You forgot to call next()on the result set:

你忘了调用next()结果集:

ResultSet numOfMatchResult = prepareSQL.executeQuery();
int numOfMatch = 0;
if (rs.next() {    
    numOfMatch = numOfMatchResult.getInt(1);
}

If that is not sufficient to solve the problem, paste the whole stack trace of the exception: it contains meaningful information.

如果这不足以解决问题,请粘贴异常的整个堆栈跟踪:它包含有意义的信息。