Search code examples
javasqlweb-servicesresthashbytes

Java PreparedStatement: Binding Parameter to HASHBYTES


Right now, I have the prepared statement below, which works:

SELECT email, password
FROM Professor 
WHERE email = ? AND password = HASHBYTES('SHA1','" + password + "') 

p.setString(1, email);

But when I try to parameterize the value to be encrypted by HASHBYTES (in this case, the variable 'password'), there is some kind of reading/type/conversion error that does not return results. This is the code that doesn't work:

SELECT email, password
FROM Professor 
WHERE email = ? AND password = HASHBYTES('SHA1', ?) 

p.setString(1, email);
p.setString(2, password);

I get no error message at all; the resultset returns "-3" in the rowCount property. I'm using SQL Server.

Passing the 'password' placeholder like this: '?' doesnt work either. What would be the correct way to parameterize this query?


Solution

  • Using the information you all pointed out and researching about how to convert types in SQL Server, I've came to the following code:

    select email, password
      from Professor
     where email = ?
       and password = hashbytes('sha1', convert(varchar, ?))
    

    Please, verify if it works for you!