How can I know if a SQL select query from Java to SQL Server didn't return any results?

How can I know if a SQL select query from Java to SQL Server didn't return any results?



I am trying to know if a SELECT query made from Java to SQL Server doesn't return any results, because I'm trying to do a "verification" in the database to know if a User already exists, so if the SELECT query returned false, for example, I know that the given user doesn't exist and I can add it to the database.


SELECT


User


SELECT


false


user


Connection c = ConexionSQL.Conexion.getConection();
try
Statement select = c.createStatement();
ResultSet r = select.executeQuery("SELECT * FROM Usuario WHERE id="+id);

if(r.next())
//Show message that the user already Exists

else
//Add user to the database


catch(Exception ex)
System.out.println("No se puedo realizar el select");
ex.printStackTrace();






What exactly is your question? The code you show already does what you want. You'll need to explain why it doesn't work for you or why you want a different solution.

– Mark Rotteveel
Sep 18 '18 at 10:59





1 Answer
1



I am guessing that your code works, but instead of using r.next() you can use r.isBeforeFirst(), because if there's data, you won't have to backtrack to get it back.


r.next()


r.isBeforeFirst()



In summary, isBeforeFirst() returns false if there cursor is not before the first row or if there are no rows.


isBeforeFirst()






isBeforeFirst() is optional for TYPE_FORWARD_ONLY result sets, so relying on this is not a good idea as it can throw SQLFeatureNotSupportedException

– Mark Rotteveel
Sep 18 '18 at 10:58



isBeforeFirst()


TYPE_FORWARD_ONLY


SQLFeatureNotSupportedException



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

PHP code is not being executed, instead code shows on the page

Administrative divisions of China

Cardinality of the set of algorithms