Executing sql query using PreparedStatement

I have the following code in a 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 starting and reaching the line int numOfMatch = numOfMatchResult.getInt(1); it throws an exception - java.sql.SQLException . I checked it and saw that it was because executeQuery() was empty. this happens, although I have 2 fields in the persons table created using MySQL, id (text) with the value "300" and password (text) with the value "500". and of course I check it when loginID and loginPassword with the same 2 values. I checked all other questions about connecting to the database and everything was fine .. so I think the problem is the SQL syntax in strSQLcount .

+6
source share
1 answer

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

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

If this is not enough to solve the problem, insert the entire trace of the exception stack: it contains meaningful information.

+6
source

Source: https://habr.com/ru/post/922148/


All Articles