Prepared Statement Error

Jimmy picture Jimmy · Apr 1, 2012 · Viewed 9.1k times · Source

Recently just changed my statements in SQL to prepared statements for security reasons and here's what I came up with..

Unfortunately it's coming up with an cannot find error on the

"SELECT * FROM owner WHERE username = ? AND" + "password = ?;"; 

The whole error:

Cannot find symbol: symbol: method prepareStatement(java.lang.String) location: variable dbAccess of type HolidayExchange.DBAccess

I realise that it's finding a String when it should be a preparedstatement but this is how I always see it in examples etc.

I'm probably doing something idiotic but any help solving this would be really helpful!

The whole method:

DBAccess dbAccess = new DBAccess();

        String sql = "SELECT * FROM owner WHERE username = '?' AND"+
                " password = '?'";

        PreparedStatement ps = dbAccess.prepareStatement(sql);

        ps.setString(1,u);
        ps.setString(2,p);

        ResultSet rs = dbAccess.executeQuery2(ps);
        User user = new User();
        while (rs.next()){
            user.setFirstname(rs.getString("firstname"));
            user.setSurname(rs.getString("surname"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
        }

        rs.close();
        dbAccess.close();

        if(user.getUsername().length()==0){
            return null;
        }else{
            return user;
        }
    } catch (Exception e) {
        return null;
    }
}`

Answer

thumbmunkeys picture thumbmunkeys · Apr 1, 2012

There is a space missing

      // becomes ANDpassword in the resulting string:
     "SELECT * FROM owner WHERE username = ? AND" + "password = ?;"; 

should be

     // space added before passsword:
     "SELECT * FROM owner WHERE username = ? AND" + " password = ?;";