Java从MySQL获取特定单元格数据遇异常:结果集未启动求助
Hey there, let's tackle that frustrating "Before start of result set" exception you're hitting when trying to fetch values from the Balance column.
What's causing this?
When you run a query with JDBC and get a ResultSet, the cursor starts positioned before the first row of your results. If you try to call getInt("Balance") (or any other getter method) right away without moving the cursor to a valid row, JDBC throws this exception to tell you there's no row selected to read from.
How to fix it
You need to explicitly move the cursor to the first row using rs.next() before trying to access any column values. Plus, it's smart to check the return value of rs.next()—if it returns false, that means your query didn't return any matching rows, so you can handle that case gracefully too.
Here's how to adjust your code (I'll fill in the missing parts of your snippet to show the full flow):
private void OKbtnActionPerformed(java.awt.event.ActionEvent evt) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { String password = PassJP.getText(); int passint = Integer.parseInt(password); // Establish connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/banking..."); // Use PreparedStatement to avoid SQL injection (always better practice!) String query = "SELECT Balance FROM your_table_name WHERE your_condition = ?"; // Replace with your actual table/condition pstmt = conn.prepareStatement(query); pstmt.setInt(1, passint); // Set parameter for your condition rs = pstmt.executeQuery(); // Move cursor to first row AND check if a row exists if (rs.next()) { int balance = rs.getInt("Balance"); // Do something with the balance value here—like display it or process it System.out.println("Balance retrieved: " + balance); } else { // No matching record found—handle this (show error message, etc.) System.out.println("No record found with the provided password"); } } catch (NumberFormatException e) { System.err.println("Invalid password format—please enter an integer!"); e.printStackTrace(); } catch (SQLException e) { System.err.println("Got an exception! " + e.getMessage()); e.printStackTrace(); } finally { // Always close resources to avoid leaks try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
Key reminders:
- Always call
rs.next()first: This is the most critical fix for your exception. - Check the return value: Don't assume there's always a row returned—handle empty resultsets to avoid unexpected behavior.
- Use
PreparedStatement: It's safer than plainStatementbecause it prevents SQL injection, and it's easier to manage dynamic parameters. - Clean up resources: Closing
ResultSet,PreparedStatement, andConnectionin afinallyblock ensures you don't leave database connections hanging.
内容的提问来源于stack exchange,提问作者user9446596

