如何判断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()returnstrue, 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). Callingnext()shifts it to the first row (position0) if it exists, returningtrue. If no rows exist, it stays at-1and returnsfalse. - SQL Injection Risk: Your original code used string concatenation to build the query, which is a major security hazard.
PreparedStatementwith 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
相关产品推荐
相关产品推荐

