码迷,mamicode.com
首页 > 数据库 > 详细

JDBC(3)ResultSet

时间:2018-10-12 23:51:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:method   abs   ring   close   操作   where   nts   getc   public   

ResultSet

在执行查询(select)时候使用

这是一个结果对象,该对象包含结果的方法但指针定位到一行时

调用Statement 对象的 executeQuery(sql)可以得到结果集

可以通过调用getXxx(index) 或getXxx(columnName)获取每一行的值,从1开始

注意使用之后要关闭

 

方法:

->void close() throws SQLException:释放ResultSet方法

->boolean absolute(int row):将结果集的记录指针移动到第row行。

->void beforeFirst():将ResultSet的记录指针定位到首行之前。

->boolean first():将指针移到首行。

->boolean next():将指针记录定位到下一行。

->boolean last():将指针移到最后一行。

->boolean afterLast():将ResultSet的记录定位到最后一行。

 

 以上介绍的方法中经常使用到的是:next()和close()

其他的使用的时候,可以参考介绍的文档,这里主要测试是常用的

 

@Test
    public void ResultSetMethod() {
        // 获取 id = 4 的 student 数据表的记录,并打印
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try {
            // 1. 获取 Connection
            conn = getConnection();
            // 2.获取Statement
            statement = (Statement) conn.createStatement();
            // 3.准备sql
            String sql = "SELECT id, sname, sclass from student where id = 4";
            // 4.执行查询
            rs = statement.executeQuery(sql);
            // 5.处理ResultSet
            if (rs.next()) {
                int id = rs.getInt(1);// 获取数据库的id属性
                String name = rs.getString(2);// 获取数据库的 sname属性
                int sclass = rs.getInt(3);// 获取数据库的sclass属性

                System.out.println(id);
                System.out.println(name);
                System.out.println(sclass);
            }
            // 6.关闭
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        if (rs != null) {
          try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
          }
        }
        if (statement != null) {
          try {
            statement.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
        }
        if (conn != null) {
          try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
          }
        }

        }
    }

 

 对于executeQuery(sql)主要是执行查询操作

在世用getXxxx的时候,是根据我们查询到的列的属性进行设置分配的(可以理解数据库的每个数据表的列)

在程序的最后,一定要记得关闭释放资源

关闭的流程:由里到外

所谓关闭流程就是:先获取的资源后关闭,后获取的资源先关闭

 

JDBC(3)ResultSet

标签:method   abs   ring   close   操作   where   nts   getc   public   

原文地址:https://www.cnblogs.com/Mrchengs/p/9780629.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!