0

I have DAO method in Java which looks like this:

private boolean validateUser(String email, String username) throws SQLException {
    return stmt.execute(
        "SELECT NOT EXISTS" +
        "(SELECT id from Math_Hub.Users_Information " +
        "WHERE username = '" + username + "' OR email = '" + email + "')");
}

The method returns true even if username already exists in database. Why is that?

I tried to test it by hand and the following SQL statement

SELECT NOT EXISTS
(SELECT id from Math_Hub.Users_Information
WHERE username = 'Eren' OR email = 'erenyeager@gmail.com')

This worked perfectly.

Robert
  • 7,394
  • 40
  • 45
  • 64
  • 1
    Please use [prepared statements](https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html). As is, your code is wide open to [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. – Robert Mar 23 '22 at 03:40

1 Answers1

0

NOT EXISTS always return 1 if no row matches in the where clauses. Either use EXISTS or you can go with select query and later check if anything is received in the resultset( select * or select count(*)).

Chetna R
  • 21
  • 1