首页 > 解决方案 > 来自数据库的 Java JTable 数据

问题描述

我是 java 新手,在 jtable 中显示连接表/查询时需要帮助。

首先,我已经完成了显示来自 1 个表的数据,即:

我正在使用 DAO 模式,它具有工厂、接口、实现、实体和视图。

那么如果我从其他表中选择数据呢?

这是我在实现中获取书籍的获取方法

 public List get(String find) {
    try {
        ps = db.connect().prepareStatement("SELECT * FROM books WHERE title like ? ");
        ps.setString(1, "%" + find + "%");

        status = db.execute(ps);
        if (status) {
            books = db.get_result();
            listBooks = new ArrayList<>();

            while (books.next()) {
                entity_books b = new entity_books();
                b.setId(books.getInt(1));
                b.setId_category(books.getInt(2)); 
                b.setTitle(books.getString(3));
                listBooks.add(b);
            }
            books.close();
            return listBooks;
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return null;
}

然后在我看来:

listBooks = booksDAO.get(find.getText());
    model = (DefaultTableModel) book_table.getModel();
    model.setRowCount(0);

    listBooks.forEach((data) -> {
        model.addRow(new Object[]{
            data.getId(),
            data.getId_category(),
            data.getTitle(),

        });
    });

这很好用,但我希望查询加入表,这样我就可以看到类别名称而不仅仅是 ID 类别。我可以进行查询,但如何将其应用于我的代码?

这是连接表的查询

select title,category from book b
join category c on c.id = b.id_category    

通常,如果我只选择 1 个表,我会将其插入其实体( book table -> book entity ),那么如何处理多个表?

标签: javamysqljdbc

解决方案


我没有使用准备好的语句,但是这段代码对我有用。

String sql = "SELECT * FROM customer c JOIN company cmp ON c.company_idcompany = cmp.idcompany";

        ResultSet rs = stmt.executeQuery(sql);
        //STEP 5: Extract data from result set
        while (rs.next()) {
            //Retrieve this from customer table
            int id = rs.getInt("idcustomer");
            //Retrieve this from customer table
            String username = rs.getString("company_username");

            //Display values
            System.out.println("ID: " + id);
            System.out.println("Username: " + username);
        }

推荐阅读