You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断SQL查询语句执行后ResultSet是否返回数据或为空?

How to Check if a ResultSet Returns Data in Java JDBC

Hey there! Let's tackle your problem step by step, fix the code issues, and cover some important best practices along the way.

The Core Fix: Checking for ResultSet Data

Right after running executeQuery(), your ResultSet starts positioned before the first row. To verify if there's any data returned, you just need to use the next() method:

  • If next() returns true, it means the cursor successfully moved to a valid row with data.
  • If it returns false, there are no rows in the ResultSet.

Updated & Fixed Code

Here's your code with the correct check, syntax fixes (like the misplaced parentheses after else), and a critical security improvement to avoid SQL injection:

try{ 
    // Use PreparedStatement instead of Statement to prevent SQL injection!
    String sql = "SELECT * from BOOKS WHERE ISBN_No = ?"; 
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, line); // Safely bind the ISBN value
    
    ResultSet rs = pstm.executeQuery(); 
    
    if(rs.next()) { // This checks if at least one row exists
        // Uncomment below if you need to re-read the result later (cursor moves forward once)
        // rs.beforeFirst();
        displayBookInfo(line); 
    } else { 
        System.out.println("No book found"); 
    } 
    
    // Close resources in reverse order of creation to avoid leaks
    rs.close();
    pstm.close(); 
} catch (SQLException e) { 
    e.printStackTrace(); 
    System.out.println("Failed to search for book with ISBN: " + line ); 
    noException = false; 
}

Key Details to Remember:

  • How next() works: When you first get the ResultSet, the cursor sits at position -1 (before the first row). Calling next() shifts it to the first row (position 0) if it exists, returning true. If no rows exist, it stays at -1 and returns false.
  • SQL Injection Risk: Your original code used string concatenation to build the query, which is a major security hazard. PreparedStatement with parameter placeholders (?) separates SQL logic from user input, eliminating this risk entirely.
  • Resource Cleanup: Always close ResultSet, Statement/PreparedStatement, and Connection in reverse order of how you created them to prevent resource leaks.

内容的提问来源于stack exchange,提问作者Swagatg Gautam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:09:10