Mysql 发表于 2017-07-10 数据的遍历 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647private static void listBook2() throws Exception { Connection con = dbUtil.getCon(); // 获取连接 String sql = "select * from t_book"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); // 返回结果集ResultSet while (rs.next()) { int id = rs.getInt("id"); // 获取第一个列的值 编号id String bookName = rs.getString("bookName"); // 获取第二个列的值 图书名称 bookName float price = rs.getFloat("price"); // 获取第三列的值 图书价格 price String author = rs.getString("author"); // 获取第四列的值 图书作者 author int bookTypeId = rs.getInt("bookTypeId"); // 获取第五列的值 图书类别id System.out.println("图书编号:" + id + " 图书名称:" + bookName + " 图书价格:" + price + " 图书作者:" + author + " 图书类别id:" + bookTypeId); System.out .println("============================================================="); }}//第一种方法private static List<Book> listBook3()throws Exception{//List是一个泛型,返回一个对象 List<Book> bookList=new ArrayList<Book>(); //相当于建立了一个数组 Connection con = dbUtil.getCon(); // 获取连接 String sql = "select * from t_book"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); // 返回结果集ResultSet while (rs.next()) { int id = rs.getInt("id"); // 获取第一个列的值 编号id String bookName = rs.getString("bookName"); // 获取第二个列的值 图书名称 bookName float price = rs.getFloat("price"); // 获取第三列的值 图书价格 price String author = rs.getString("author"); // 获取第四列的值 图书作者 author int bookTypeId = rs.getInt("bookTypeId"); // 获取第五列的值 图书类别id Book book=new Book(id, bookName, price, author, bookTypeId);//创建一组数据 bookList.add(book);//相当于往数组里传值 } return bookList;}//第二种方法public static void main(String[] args) throws Exception { listBook2();//第一种方法的调用 List<Book> bookList=listBook3(); for (Book book : bookList) { System.out.println(book);//此处需要在Book类中重写toString方法,因为传入输出的是对象 }//第二种方法的调用}public String toString() { return "["+this.id+","+this.bookName+","+this.price+","+this.author+","+this.bookTypeId+"]";}