java - 来自数据库的 Java JTable 数据
问题描述
我是 java 新手,在 jtable 中显示连接表/查询时需要帮助。
首先,我已经完成了显示来自 1 个表的数据,即:
- 从 1 个表中选择数据
- 将结果插入其实体并将每个结果插入列表
- 返回列表以查看并将行插入到 jtable
我正在使用 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 ),那么如何处理多个表?
解决方案
我没有使用准备好的语句,但是这段代码对我有用。
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);
}
推荐阅读
- sapui5 - 呈现为下拉列表的智能字段不显示说明
- sql-server - VSS 中的还原操作失败返回 VSS_E_OBJECT_NOT_FOUND
- amazon-web-services - 什么 AWS 服务限制管理 Lambda/SQS 事件源映射?
- json - 有没有办法区分空值和没有键?
- ios - 是否有来自 Firebase Cloud Messaging 的回调以指示已收到消息?
- javascript - 找不到 url 时在地址栏中维护 url
- python - 比较并从两个数据框中删除重复项
- html - 如何使我的背景图像适合手机尺寸?
- azure-devops - 在 Azure Devops 中构建一个通用工件,并在发布时根据不同的环境注入某些变量
- aem - AEM - 如何在 OSGi 组件中检索 model-json