简体   繁体   中英

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.

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();
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM