JDBC(3)ResultSet

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的时候,是根据我们查询到的列的属性进行设置分配的(可以理解数据库的每个数据表的列)

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

关闭的流程:由里到外

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

 

相关文章