可更新和对更新敏感的结果集

可更新的结果集(说明这些都是JDBC特殊的用法,有些数据库可能不支持)

       conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

                                   ResultSet.CONCUR_UPDATABLE);

       rs.updateString("col name", "new value");

       rs.updateRow();

      

public class OtherApi {

    public static void main(String[] args) throws SQLException,

           InterruptedException {

           read();

    }

 

    static void read() throws SQLException, InterruptedException {

       Connection conn = null;

       Statement st = null;

       ResultSet rs = null;

       try {

           // 2.建立连接

           conn = JdbcUtils.getConnection();

           // conn = JdbcUtilsSing.getInstance().getConnection();

           // 3.创建语句

           st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

                  ResultSet.CONCUR_UPDATABLE);

           //ResultSet.TYPE_SCROLL_INSENSITIVEResultSet.TYPE_SCROLL_SENSITIVE区别

           //TYPE_SCROLL_SENSITIVE能够感应到数据库中的变化,即在未出查询得到结果集ResultSet时如果数据库在的

           //记录发生改变了,查询得到结果集ResultSet它能够知道.当然这样会消耗性能的.

           //TYPE_SCROLL_INSENSITIVE是不能够感应到数据库中的变化.

           // 4.执行语句

           rs = st

                  .executeQuery("select id, name, money, birthday  from user where id < 5");

 

           // 5.处理结果

           while (rs.next()) {

              int id = rs.getInt("id");

              System.out.println("show " + id + "...");

              System.out.println(id + "\t" + rs.getObject("name") + "\t"

                     + rs.getObject("birthday") + "\t"

                     + rs.getObject("money"));

              //在结果集中修改结果集,数据库也修改了。如下面把李四money修改为500f了。

              String name=rs.getString("name");

              if(name.equals("lisi")){

                  rs.updateFloat("money", 500f);

                  rs.updateRow();

              }

           }

       } finally {

           JdbcUtils.free(rs, st, conn);

       }

    }

}

你可能感兴趣的:(jdbc)