简体   繁体   中英

How do I check if the sql command returns null or a value?

try{
        Statement stm = conn.createStatement();

        String sql = "SELECT * from BOOKS WHERE ISBN_No = '" + line + "'";
        ResultSet rs = stm.executeQuery(sql);
        if(//values are returned) {
            displayBookInfo(line);
        }
        else (//if it is null) {
            System.out.println("No book found");
        }
        stm.close();

    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("Fail to search the book" + line );
        noException = false;
    }

After I execute the ResultSet rs = stm.executeQuery(sql);I want to check if the query returned a value or if it was empty so that I can execute either "display book details" or "no book found message". I am just confused about how I should compare and how comparison works.

This code is a security leak . You must fix this first.

You cannot include untrusted inputs in a query like this. What if someone enters, say:

1234'; DROP TABLE books CASCADE; EXECUTE 'FORMAT C: /Y'; --

In the web form? Don't try it, you'll wipe your disk. You get the point, surely.

The right way is to use stm.prepareStatement(sql) , where sql is a constant (so not something you insert user entered stuff into), using a ? where user input is needed, then calling .setString(1, line) to then tell your db driver what should go in place of the question mark.

Then, simply rs.next() , which advanced to the next row in the result (first call advances to the first row). If there are no rows left, it returns false instead. Hence, if your query returns 0 rows, the first resultSet.next() call returns false right away.

Your code also fails to close. You must use try-with-resources on everything (ResultSet, (Prepared)Statement, and most importantly the Connection), or your app will crash after a few statements.

NB: Minor nit, if all you want to know is if there's at least one result, add LIMIT 1 , and just SELECT 1 FROM instead - it's less overhead that way.

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