Search code examples
javajdbcprepared-statementresultset

preparedstatement, resultset, and query issue


The method below should take two user inputs "low and "high" from a jsp page, and use them to get a list of properties that have a price that are between the "low" and "high".

One error that I see in my tomcat-log is:

MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BETWEEN 100000.0 and 300000.0' at line 1

100000.0 and 300000.0 is the input I typed in.

public static ArrayList<Property> search(double low, double high) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;

    String query = "select * from properties"
        + "WHERE price BETWEEN ? and ?";

    try {
        ps = connection.prepareStatement(query);
        ps.setDouble(1, low);  //this should set user input = ?
        ps.setDouble(2, high); //this should set user input = ?
        rs = ps.executeQuery();

        ArrayList<Property> list = new ArrayList<>();

        while (rs.next()) {     
            Property p = new Property();    
            p.setName(rs.getString("name"));
            p.setPrice(rs.getDouble("price"));
            list.add(p);
        }       
        return list;
    } catch (SQLException e) {
        System.out.println(e);
        return null;
    } finally {
        DBUtil.closeResultSet(rs);
        DBUtil.closePreparedStatement(ps);
        pool.freeConnection(connection);
    }

}

Solution

  • You are missing a space in your query

    String query = "select * from properties"
        + " WHERE price BETWEEN ? and ?";
    

    as you had it the word would become propertiesWHERE