0

I have query which must return a boolean but I always get the same result. I have tried this:

 boolean exist=stmt.execute("select exists(select 1 from calcul where 
 to_char(date, 'YYYY-MM')=to_char("+dates+", 'YYYY-MM') AND
 idproduit="+codeP+" AND ppa="+PPA+" AND tr="+TR+" AND net="+NET+" AND 
 dateper='"+datePer+"')");

The result is always true, never false; why?

2
  • 2
    the = sign is the assignment sign, while == is a comparison sign. Commented Nov 23, 2015 at 21:40
  • Please use a PreparedStatement, do not concatenate SQL queries like that. You also need to use executeQuery() as clearly documented in the JavaDocs Commented Nov 23, 2015 at 22:17

2 Answers 2

2

The true just means that there is a result, as stated in the javadoc of execute():

Returns:
true if the first result is a ResultSet object; false if the first result is an update count or there is no result.

You need to call getResultSet() to get the actual result.

Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at the JavaDocs for Statement#execute(String)

Returns:
true if the first result is a ResultSet object; false if it is an update count or there are no results

You could use Statement#executeQuery(String) which will return a ResultSet, from which you will then need to inspect the result of the first row

Something like...

try (Statement stmt = con.createStatement()) {
    try (ResultSet rs = stmt.executeQuery("select exists(select 1 from calcul where to_char(date, 'YYYY-MM')=to_char("+dates+", 'YYYY-MM') AND idproduit="+codeP+" AND ppa="+PPA+" AND tr="+TR+" AND net="+NET+" AND dateper='"+datePer+"')")) {
        if (rs.next()) {
            boolean exists = rs.getBoolean(1);
        }
    }
} catch (SQLException exp) {
    exp.printStackTrace();
}

for example.

Having said that, I'd strongly encourage you to use a PreparedStatement, see Using Prepared Statements for more details

For example...

try (PreparedStatement stmt = con.prepareStatement("select exists(select 1 from calcul where to_char(date, 'YYYY-MM')=to_char(?, 'YYYY-MM') AND idproduit=? AND ppa=? AND tr=? AND net=? AND dateper='?')")) {
    stmt.setString(1, dates);
    stmt.setString(2, codeP);
    stmt.setString(3, PPA);
    stmt.setString(4, TR);
    stmt.setString(5, NET);
    stmt.setString(6, datePer);
    try (ResultSet rs = stmt.executeQuery()) {
        if (rs.next()) {
            boolean exists = rs.getBoolean(1);
        }
    }
} catch (SQLException exp) {
    exp.printStackTrace();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.