为什么我只能从表中获得一条记录?

时间:2019-06-04 12:16:02

标签: java sql swing

我正在使用Employee_id从表中搜索记录,同一Employee_id在同一日期在表中有两条记录,但是根据Employee_id搜索记录后仅得到一条记录。

我的表格中有以下几列:

Device_ID, Employee_id, Employee_Name, Employee_Ext, Issue_Date

这是我的Java代码:

public void actionPerformed(ActionEvent ae) {
  try {
    String str = tf5.getText();
    Connection con = DB.getConnection();
    PreparedStatement st = con.prepareStatement("select * from issuedevices where Employee_id=?");
    st.setString(1, str);
    ResultSet rs = st.executeQuery();

    // Vector v = new Vector();
    if (rs.next()) {
      frame1 = new JFrame("Database Search Result");
      frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame1.setLayout(new BorderLayout());
      //TableModel tm = new TableModel();
      DefaultTableModel model = new DefaultTableModel();
      model.setColumnIdentifiers(columnNames);
      table = new JTable();
      table.setModel(model);
      table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
      table.setFillsViewportHeight(true);
      JScrollPane scroll = new JScrollPane(table);
      scroll.setHorizontalScrollBarPolicy(
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      scroll.setVerticalScrollBarPolicy(
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      //  from = (String) c1.getSelectedItem();
      String id = "";
      String Device_ID = "";
      String Employee_id = "";
      String Employee_Name = "";
      String Employee_Ext = "";
      String Issue_Date = "";

      try {
        pst = con.prepareStatement("select * from issuedevices where Employee_id='" + str + "'");
        ResultSet rs1 = pst.executeQuery();
        int i = 0;
        if (rs1.next()) {
          id = rs1.getString("id");
          Device_ID = rs1.getString("Device_ID");
          Employee_id = rs1.getString("Employee_id");
          Employee_Name = rs1.getString("Employee_Name");
          Employee_Ext = rs1.getString("Employee_Ext");
          Issue_Date = rs1.getString("Issue_Date");

          model.addRow(new Object[] {
            id,
            Device_ID,
            Employee_id,
            Employee_Name,
            Employee_Ext,
            Issue_Date
          });
          i++;
        }
        if (i < 1) {
          JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
        }
        if (i == 1) {
          System.out.println(i + " Record Found");
        } else {
          System.out.println(i + " Records Found");
        }
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
      }
      frame1.add(scroll);
      frame1.setVisible(true);
      frame1.setSize(400, 300);
    }

    // st.close();
    // rs.close();
  } catch (Exception e) {
    JOptionPane.showMessageDialog(null, "Name not Found");
  }
}

1 个答案:

答案 0 :(得分:6)

您没有循环,因此只能得到一个结果。尝试更改

if (rs1.next())

while (rs1.next())