(异常)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 <code>ResultSet</code> cursor is initially positioned
     * before the first row; the first call to the method
     * <code>next</code> makes the first row the current row; the
     * second call makes the second row the current row, and so on.
     * <p>
     * When a call to the <code>next</code> method returns <code>false</code>,
     * the cursor is positioned after the last row. Any
     * invocation of a <code>ResultSet</code> method which requires a
     * current row will result in a <code>SQLException</code> being thrown.
     *  If the result set type is <code>TYPE_FORWARD_ONLY</code>, it is vendor specified
     * whether their JDBC driver implementation will return <code>false</code> or
     *  throw an <code>SQLException</code> on a
     * subsequent call to <code>next</code>.
     *
     * <P>If an input stream is open for the current row, a call
     * to the method <code>next</code> will
     * implicitly close it. A <code>ResultSet</code> object's
     * warning chain is cleared when a new row is read.
     *
     * @return <code>true</code> if the new current row is valid;
     * <code>false</code> 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 <code>ResultSet</code> cursor is initially positioned
     * before the first row;

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

因此不调用next方法就从resultSet中获取数据是不可取的。

猜你喜欢

转载自blog.csdn.net/qq_29519041/article/details/82290081