Java ResultSet isAfterLast() 方法及示例
当我们执行某些 SQL 查询(通常是 SELECT 查询)时,它们会返回表格数据。
java.sql.ResultSet 接口表示 SQL 语句返回的此类表格数据。
即 ResultSet 对象保存由执行查询数据库语句的方法(通常是 Statement 接口的 executeQuery() 方法)返回的表格数据。
ResultSet 对象有一个光标/指针,指向当前行。最初,此光标位于第一行之前。

ResultSet 接口的 isAfterLast() 方法用于确定光标是否位于 ResultSet 的末尾之后。
rs.isAfterLast();
此方法返回一个布尔值,如果光标位于 ResultSet 的末尾之后,则此值为 true,否则返回 false。
让我们使用 CREATE 语句在 MySQL 数据库中创建一个名为 MyPlayers 的表,如下所示:
CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );
现在,我们将使用 INSERT 语句在 MyPlayers 表中插入 7 条记录:
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');以下 JDBC 程序建立与数据库的连接,将表 MyPlayers 的内容检索到 ResultSet 对象中,并确定光标是否位于 ResultSet 的末尾之后。
示例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSet_isAfterLast {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to retrieve records
String query = "Select * from MyPlayers";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//Verifying whether the cursor is at the next row to the end of the ResultSet (after last).
boolean bool= rs.isAfterLast();
if(bool) {
System.out.println("Cursor is at the next row to the end of the ResultSet");
} else {
System.out.println("Cursor is not at the next row to the end of the ResultSet");
}
rs.afterLast();
if(rs.isAfterLast()) {
System.out.println("Cursor is at the next row to the end of the ResultSet");
} else {
System.out.println("Cursor is not at the next row to the end of the ResultSet");
}
}
}输出
Connection established...... Cursor is not at the next row to the end of the ResultSet Cursor is at the next row to the end of the ResultSet
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP