结果集有两种类型,即仅转发和双向。
仅转发ResultSet:其光标仅向一个方向移动的ResultSet对象称为仅转发ResultSet。默认情况下,JDBC结果集是仅转发结果集。
您可以使用ResultSet接口的next()方法移动仅向前的ResultSet的光标。它将指针从当前位置移到下一行。此方法返回一个布尔值。如果当前位置旁边没有行,则返回false,否则返回true。
因此,在while循环中使用此方法可以迭代ResultSet对象的内容。
while(rs.next()){
}
假设我们有一个名为数据集的表,其内容如下所示:
+--------------+-----------+
| mobile_brand | unit_sale |
+--------------+-----------+
| Iphone | 3000 |
| Samsung | 4000 |
| Nokia | 5000 |
| Vivo | 1500 |
+--------------+-----------+
下面的示例检索数据集表的所有记录并打印结果:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingData {
public static void main(String args[]) throws Exception {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//创建一个Statement对象
Statement stmt = con.createStatement();
//检索数据
ResultSet rs = stmt.executeQuery("select * from Dataset");
System.out.println("Contents of the table");
while(rs.next()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
}
}
}
Connection established......
Contents of the table
Brand: Iphone, Sale: 3000
Brand: Samsung, Sale: 4000
Brand: Nokia, Sale: 5000
Brand: Vivo, Sale: 1500
双向ResultSet:双向ResultSet对象是其光标向前和向后移动的对象。
createStatement()
Connection接口的方法具有一个变体,可以接受两个表示结果集类型和并发类型的整数值。
Statement createStatement(int resultSetType, int resultSetConcurrency)
要创建双向结果集,您需要将类型作为ResultSet.TYPE_SCROLL_SENSITIVE或ResultSet.TYPE_SCROLL_INSENSITIVE以及并发性传递给此方法,如下所示:
//创建一个Statement对象
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
以下示例演示了双向ResultSet的创建。在这里,我们尝试创建一个双向ResultSet对象,该对象从表名数据集中检索数据,并尝试使用previous()方法从最后到第一打印数据集表的行。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BidirectionalResultSet {
public static void main(String args[]) throws Exception {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//创建一个Statement对象
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//检索数据
ResultSet rs = stmt.executeQuery("select * from Dataset");
rs.afterLast();
System.out.println("Contents of the table");
while(rs.previous()) {
System.out.print("Brand: "+rs.getString("Mobile_Brand")+", ");
System.out.print("Sale: "+rs.getString("Unit_Sale"));
System.out.println("");
}
}
}
Connection established......
Contents of the table
Brand: Vivo, Sale: 1500
Brand: Nokia, Sale: 5000
Brand: Samsung, Sale: 4000
Brand: IPhone, Sale: 3000