java rs.next_JDBC中rs.next()的思考 | 学步园

在使用Java JDBC处理查询结果时,如果直接调用ResultSet的getInt(1)等方法可能会抛出'ResultSet没有当前行'的异常。解决这个问题需要在访问数据前先调用rs.next()来移动光标到第一行。rs.next()方法会将游标向下移动一行,返回值表示当前行是否有效。如果不调用next(),则没有行被选中,从而导致异常。
摘要由CSDN通过智能技术生成

编程过程中发现这样的问题:ResultSet rs, 当执行好查询之后操作比如 rs.getInt(1),会发生异常:

com.microsoft.sqlserver.jdbc.SQLServerException: ResultSet 没有当前行。

at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)

at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyOnValidRow(Unknown Source)

at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getterGetColumn(Unknown Source)

at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getInt(Unknown Source)

在这行之前添加了rs.next()操作就可以了,查询了一下文档才知道了原因。

java.sql

Interface ResultSet

boolean

Method Detail

next

public boolean next()

throws SQLException

Moves the cursor down 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.

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.

Returns:

true if the new current row is valid; false if there are no more rows

Throws:

这段代码的问题在于你将一个ResultSet对象直接转换成了Book对象,这是不合法的。ResultSet对象代表了一个数据库查询结果集,并不是一个Book对象。你需要使用rs.next()方法来移动ResultSet对象的指针,然后使用rs.getXXX()方法来获取每个列的值,最后将这些值赋值给一个Book对象的属性。例如: ```java if (rs.next()) { Book book = new Book(); book.setBook_ISBN(rs.getString("book_ISBN")); book.setBook_category(rs.getString("book_category")); book.setBook_name(rs.getString("book_name")); book.setBook_author(rs.getString("book_author")); book.setPublish_house(rs.getString("publish_house")); book.setPublish_time(rs.getString("publish_time")); book.setBook_price(rs.getDouble("book_price")); book.setBook_sum(rs.getInt("book_sum")); book.setBook_remain(rs.getInt("book_remain")); book.setBook_introduce(rs.getString("book_introduce")); // 检查添加的图书信息是否正确 assertEquals("456", book.getBook_ISBN()); assertEquals("计算机科学", book.getBook_category()); assertEquals("java编程思想", book.getBook_name()); assertEquals("张三", book.getBook_author()); assertEquals("机械工业出版社", book.getPublish_house()); assertEquals("2020-01", book.getPublish_time()); assertEquals(65, book.getBook_price(), 0.01); assertEquals(12, book.getBook_sum()); assertEquals(4, book.getBook_remain()); assertEquals("无", book.getBook_introduce()); } ``` 注意,这里使用了if (rs.next())来判断是否查询到了结果,并且只取第一条结果作为Book对象。如果你需要查询多条结果,需要在一个while循环逐条处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值