JDBC之读取数据库

来源:互联网 发布:微博登陆不了网络异常 编辑:程序博客网 时间:2024/05/21 12:14

今天我们介绍一下用JDBC读取数据库的记录。
首先我们看一下最简单的方法:

    private static void listBook() throws Exception {        Connection con = dbUtil.getCon();        String sql = "select * from t_book";        PreparedStatement pstmt = con.prepareStatement(sql);        ResultSet rs = pstmt.executeQuery();        while (rs.next()) {            int id = rs.getInt(1);            String bookName = rs.getString(2);            String author = rs.getString(3);            float price = rs.getFloat(4);            int bookTypeId = rs.getInt(5);            System.out.println(id + " " + bookName + " " + author + " " + price + " " + bookTypeId);        }        rs.close();        dbUtil.close(pstmt, con);    }

但是你们会注意到每次获取数据是按列的索引数来的,这样非常的不清晰,所以在实战中我们建议使用下面这种方法:

    private static void listBook() throws Exception {        Connection con = dbUtil.getCon();        String sql = "select * from t_book";        PreparedStatement pstmt = con.prepareStatement(sql);        ResultSet rs = pstmt.executeQuery();        while (rs.next()) {            int id = rs.getInt("id");            String bookName = rs.getString("bookName");            String author = rs.getString("author");            float price = rs.getFloat("price");            int bookTypeId = rs.getInt("bookTypeId");            System.out.println(id + " " + bookName + " " + author + " " + price + " " + bookTypeId);        }        rs.close();        dbUtil.close(pstmt, con);    }

ResultSet就是我们所说的结果集合,查询的结果都保存在这里,通过rs.next()来遍历查询结果。
根据面向对象的思想,我们需要把查询的结果保存起来并返回,那么我们就要做如下的操作:

    private static List<Book> listBook() throws Exception {        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();        while (rs.next()) {            int id = rs.getInt("id");            String bookName = rs.getString("bookName");            String author = rs.getString("author");            float price = rs.getFloat("price");            int bookTypeId = rs.getInt("bookTypeId");            Book book = new Book(id, bookName, author, price, bookTypeId);            bookList.add(book);        }        rs.close();        dbUtil.close(pstmt, con);        return bookList;    }

现在我们知道如何从数据库中读取记录信息。那么对一些非简单信息,比如小说或者电影,我们又应该怎么记录和读取呢?
欲知后事如何,且听下回分解。

0 0
原创粉丝点击