可滚动结果集与分页技术

可滚动的结果集

       Statement st =

       connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,      ResultSet.CONCUR_UPDATABLE);

       ResultSet rs = st.executeQuery(sql);

       rs.beforeFirst();//定位到第一行的前面

rs.afterLast();//定位到最后一行的下一行去,若想读数据则向前移

rs.first();//定位到第一行

rs.isFirst();//判断是不是第一行

rs.last();//定位到最后一行

rs.isLast();//判断是不是最后一行

       rs.absolute(9);//定位到那一行

rs.moveToInsertRow();

      

public class ScrollTest {

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

       scroll();

    }

    static void scroll() throws SQLException {

       Connection conn = null;

       Statement st = null;

       ResultSet rs = null;

       try {

           // 2.建立连接

           conn = JdbcUtils.getConnection();

           st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

                  ResultSet.CONCUR_READ_ONLY);

           rs = st

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

           while (rs.next()) {

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

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

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

                     + rs.getObject("money"));

           }

 

           System.out.println("------------");

           rs.absolute(5);//定位到第5行去

           if (rs.previous()){//定位到前一行去

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

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

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

            + rs.getObject("money"));

           }

       } finally {

           JdbcUtils.free(rs, st, conn);

       }

    }

    //用可流动的结果集进行分页

    static void scroll2() throws SQLException {

       Connection conn = null;

       Statement st = null;

       ResultSet rs = null;

       try {

           // 2.建立连接

           conn = JdbcUtils.getConnection();

           st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

                  ResultSet.CONCUR_READ_ONLY);

           rs = st

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

           while (rs.next()) {

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

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

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

                      + rs.getObject("money"));

           }

 

           System.out.println("------------");

           rs.absolute(150);//定位到150

           int i = 0;

           while (rs.next() && i < 10) {   //向下读取10条记录

              i++;

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

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

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

                     + rs.getObject("money"));

           }

       } finally {

           JdbcUtils.free(rs, st, conn);

       }

    }

    //说明,这种分页效率很低,它是由先读到内存当中去,然后再选择哪些列.这种方法就为了那些不支技分页的数据库使用的.

}

 

你可能感兴趣的:(sql)