ResultSet可滚动和可更新的结果集/

来源:互联网 发布:淘宝发布面皮类目选择 编辑:程序博客网 时间:2024/06/10 04:37
要让ResultSet可以滚动个和更新,必须在创建Statement对象的时候使用下面的方式指定对应的参数:
Statement stmt = conn.createStatement(type, concurrency);
对于PreparedStatement,使用下面的方式指定参数:
PreparedStatement pstmt = conn.prepareStatement(sql, type, concurrency);
其中,type表示ResuleSet的类型,而concurrency表示是否可以使用ResuleSet来更新数据库。
type和concurrency的取值以及含义:
    ResultSet.TYPE_FORWARD_ONLY - 结果集不能滚动,这事默认值;
    ResultSet.TYPE_SCROLL_INSENSITIVE - 结果集可以滚动,但ResuleSet对数据库中发送的数据改变不敏感;
    ResultSet.TYPE_SCROLL_SENSITIVE -  结果集可以滚动,并且ResuleSet对数据库中发生的改变敏感
    ResultSet.CONCUR_READ_ONLY - 只读结果集,不能用于更新数据库;
    ResultSet.CONCUR_UPDATABLE - 可更新结果集,可以用于更新数据库;
    当使用TYPE_SCROLL_INSENSITIVE或者TYPE_SCROLL_SENSITIVE来创建Statement对象时,可以使用ResultSet 的 first()/last()/beforeFirst()/afterLast()/relative()/absolute()等方法在结果集中随意前后移动。
提示:即使使用了CONCUR_UPDATABLE参数来创建Statement,得到的记录集也并非一定是“可更新的”,如果你的记录集来自于合并查询,即该查询的结果来自多个表格,那么这样的结果集就可能不是可更新的结果集。可以使用ResuleSet类的getConcurrency()方法来确定是否为可更新的的结果集。如果结果集是可更新的,那么可使用ResultSet的updateRow(),insertRow(),moveToCurrentRow(),deleteRow(),cancelRowUpdates() 等方法来对数据库进行更新。
例子:
 Connection con = null;
 PreparedStatement ps = null;
 ResultSet rs = null;
 String sql = "select column1,column2 from table where ...";
 con = ConnectionFactory.getConnection(true);
 try {
  con.setAutoCommit(false);
  ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
  rs = ps.executeQuery();
  while(rs.next()){
   String column1 = rs.getString("column1");
   String ss = column1 + "aa";
   rs.updateString("column1", ss);
   rs.updateString("column2", "abc");
   rs.updateRow();
  }
  ps.close();
  rs.close();
  con.commit();
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }finally{
  con.close();
 }
注意:在jdbc中使用可更新的结果集来更新数据库,不能使用"select * from table"方式的SQL语句,必须将它写成如下两种形式之一:
 1.select table.* from table
 2.select column1,column2... from table
原创粉丝点击