JDBC的结果集有很多类型。这些结果集有不同的特性,以满足各种需要。这在高性能的JDBC数据操作中有着重要应用。下面是一个应用实例:
一、测试代码
package lavasoft.common;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC可滚动可更新感知更新结果集测试
*
* @author leizhimin 2009-12-8 20:09:03
*/
public class TestResultSet {
public static void main(String[] args) {
testScrollResultSet();
testUpdateResultSet();
}
/**
* 可更新结果集更新测试
*/
public static void testUpdateResultSet() {
Connection conn = DBToolkit.getConnection();
String sql = "SELECT * FROM book";
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sql);
System.out.println("---------原结果集--------");
while (rs.next()) {
System.out.println("[行号:" + rs.getRow() + "] " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
System.out.println("---------插入一条记录--------");
rs.first();
//将光标移动到插入行上
rs.moveToInsertRow();
//构建行数据
rs.updateString(2, "xxxx");
rs.updateString(3, "x");
//插入一行
rs.insertRow();
System.out.println("-------------更新一条记录-------------");
rs.absolute(3);
//构建行数据
rs.updateString(2, "uuuu");
rs.updateString(3, "u");
rs.updateRow();
System.out.println("---------插入更新后的结果集--------");
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("[行号:" + rs.getRow() + "] " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
}
/**
* 可滚动结果集滚动测试
*/
public static void testScrollResultSet() {
Connection conn = DBToolkit.getConnection();
String sql = "SELECT * FROM book";
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("[行号:" + rs.getRow() + "] " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
}