JDBC(4)-Result结果集

1、Result结果集的引入

  当我们查询数据库时,返回的是一个二维的结果集,我们这时候需要使用ResultSet来遍历结果集,获取每一行的数据。

2、使用Result遍历查询结果

  boolean next():将光标从当前位置向前移一行。

  String getString(int columnIndex):以java编程语言中String的形式获取此ResultSet对象的当前行中指定列的值。

  String getString(int columnLabel):以java编程语言中String的形式获取此ResultSet对象的当前行中指定列的值。

示例:

public class JDBCDemo8 {

    private static MysqlUtil dbUtil = new MysqlUtil();
    /**
     * 遍历查询结果
     * @throws Exception
     */
    private static void listEmp() throws Exception{
        Connection conn = dbUtil.getConnection();
        String sql ="select * from emp2";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();//返回一个resultSet结果集
        while(rs.next()){
            //String getString(int columnIndex)
            int id = rs.getInt(1);//获取第一个列的值 id
            String name = rs.getString(2);
            //String getString(int columnLabel) 这个好
            Double salary = rs.getDouble("salary");
            int age = rs.getInt("age");
            System.out.println("雇员id:"+id+",姓名:"+name+",薪水:"+salary+",年纪:"+age);
            System.out.println("=================");
        }
    }
    
    private static List<Emp> listEmp2() throws Exception{
        List<Emp> empList = new ArrayList<Emp>();
        Connection conn = dbUtil.getConnection();
        String sql ="select * from emp2";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            int id = rs.getInt(1);
            String name = rs.getString(2);
            Double salary = rs.getDouble("salary");
            int age = rs.getInt("age");
            Emp emp = new Emp(id,name,salary,age);
            empList.add(emp);
        }
        return empList;
    }
    
    public static void main(String[] args) throws Exception{
        listEmp();
        List<Emp> empList = listEmp2();
        for(Emp emp:empList){
            System.out.println(emp);
        }
    }

}

  

原文地址:https://www.cnblogs.com/sylovezp/p/4203863.html