我是java新手,我需要帮助在jtable中显示连接表/查询。
首先,我已经完成了从1个表中显示数据:
我正在使用DAO模式,它具有工厂,接口,实现,实体和视图。
那么如果我从其他表中选择数据怎么办?
这是我在获取图书的实现中的get方法
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 - &gt; book entity),那么如何处理多个表呢?
答案 0 :(得分:1)
我没有使用预准备语句,但这段代码适用于我。
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);
}