sql查询使用PreparedStatement执行

URL*_*L87 6 java sql servlets prepared-statement executequery

我在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);
Run Code Online (Sandbox Code Playgroud)

在运行并到达该行时,int numOfMatch = numOfMatchResult.getInt(1);它会抛出异常 - java.sql.SQLException.我检查了一下,看到它是因为executeQuery() 没有人找到它.它虽然我在persons表中创建,使用MySQL创建了2个字段 - id (text)值为"300"且password (text)值为"500".当然还有我的时候检查loginIDloginPassword用相同的2个值.我检查了关于与DB的连接的所有其他事情,它没关系..所以我认为问题出在SQL语法中strSQLcount.

JB *_*zet 6

你忘了打电话next()给结果集:

ResultSet numOfMatchResult = prepareSQL.executeQuery();
int numOfMatch = 0;
if (rs.next() {    
    numOfMatch = numOfMatchResult.getInt(1);
}
Run Code Online (Sandbox Code Playgroud)

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