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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ