我已经做了足够的搜索来解决我已经部分完成的问题,但是有一个错误一直困扰着我。我正在尝试根据条件从数据库中获取数据。我有一个带有外键列的表'user_branch' branchID 应该在另一个表“分支”中获取对应的分支名称,我应该将结果显示到 JTable 中。当我执行 System.out.println 时,我得到了所有结果,但是当我显示时它只返回最后一行在 JTable(branchJTable) 中。这是我正在使用的代码
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
忘记前 3 行,因为它是我用来获取用户 ID 的另一个 JTable 事件,以用作获取分配给他的特定用户分支的条件。分配给用户的分支是动态的,因此使用 StringBuilder。我应该将结果显示到另一个名为 branchJTable 的 JTable 中,它只显示最后一行。任何帮助将不胜感激!