(异常)java.sql.SQLException: 未调用 ResultSet.next

当用ResultSet接收来自数据库查询的结果集时,即使结果集只有一条数据,也需要用到resultSet.next()函数移动游标获取数据。
不然会报未调用 ResultSet.next异常

错误写法

try {
    pstm=connection.prepareStatement("select * from account where card_id=?");
    pstm.setInt(1, card_id);
            
    resultSet = pstm.executeQuery();
        account.setCard_id(resultSet.getInt(1));
        account.setUsername(resultSet.getString(2));
        account.setPassword(resultSet.getString(3));
        account.setBalance(resultSet.getDouble(4));
        account.setMobile(resultSet.getString(5));
 
} 

正确写法

  pstm=connection.prepareStatement("select * from account where card_id=?");
   pstm.setInt(1, card_id);
   resultSet = pstm.executeQuery();
   while (resultSet.next()) {
       account.setCard_id(resultSet.getInt(1));
       account.setUsername(resultSet.getString(2));
       account.setPassword(resultSet.getString(3));
       account.setBalance(resultSet.getDouble(4));
       account.setMobile(resultSet.getString(5));
   }

ResultSet.next 注释信息

public interface ResultSet extends Wrapper, AutoCloseable {
 
    /**
     * Moves the cursor forward one row from its current position.
     * A ResultSet cursor is initially positioned
     * before the first row; the first call to the method
     * next makes the first row the current row; the
     * second call makes the second row the current row, and so on.
     * 

* When a call to the next method returns false, * the cursor is positioned after the last row. Any * invocation of a ResultSet method which requires a * current row will result in a SQLException being thrown. * If the result set type is TYPE_FORWARD_ONLY, it is vendor specified * whether their JDBC driver implementation will return false or * throw an SQLException on a * subsequent call to next. * *

If an input stream is open for the current row, a call * to the method next will * implicitly close it. A ResultSet object's * warning chain is cleared when a new row is read. * * @return true if the new current row is valid; * false if there are no more rows * @exception SQLException if a database access error occurs or this method is * called on a closed result set */ boolean next() throws SQLException;

从此接口的方法注释中第二行和第三行可以看见

A ResultSet cursor is initially positioned
* before the first row;

游标的初始位置为第一行的前面。

因此不调用next方法就从resultSet中获取数据是不可取的。
————————————————
版权声明:本文为CSDN博主「Anakki」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_29519041/article/details/82290081

你可能感兴趣的:((异常)java.sql.SQLException: 未调用 ResultSet.next)