我使用model.setRowCount(0);
来刷新表格,但是当我更新/删除数据时,我遇到了java.lang.ArrayIndexOutOfBoundsException: -1
。
private void fillTable() {
try {
model.setRowCount(0); // model is defaultdatamodel
sql = "Select * from tbphonebook";
Class.forName(driver).newInstance(); //driver already declared
con = DriverManager.getConnection(url + db, uid, pwd); //con is Connection
st = con.createStatement(); //st is statement
rs = st.executeQuery(sql); //rs is resultSet
int i = 0;
while (rs.next()) {
id = rs.getString("id");
fnam = rs.getString("firstname");
lnam = rs.getString("lastname");
add = rs.getString("address");
cp = rs.getString("cp");
model.addRow(new Object[]{id, fnam, lnam, add, cp});
i++;
if (i < 1) {
JOptionPane.showMessageDialog(null, "No record \nfound!", "warning", JOptionPane.ERROR_MESSAGE);
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
以下是我的删除查询代码
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == delete) {
sql = "delete from tbphonebook where id='" + in + "'";
if ( !"".equals(ids.getText())) {
int ch = JOptionPane.showOptionDialog(null, "You are about to delete this contact. \n Do you wish to continue?","Warning!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null,null,null);
if (ch == 0) {
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, uid, pwd);
st = con.createStatement();
st.executeUpdate(sql);
model.fireTableDataChanged();
con.close();
JOptionPane.showMessageDialog(null, "Contact Deleted!!!", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
clearFields(); // clear all text fields
fillTable();
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Choose a contact then continue", "Nothing to delete", JOptionPane.WARNING_MESSAGE);
}
}
}
}