我这里有一个代码,当我选择一行并点击按钮时,只删除1行。
int row = tblRecords.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tblRecords.getModel();
selected = model.getValueAt(row, 0).toString();
selected2 = model.getValueAt(row, 1).toString();
if(row>=0)
{
int confirm = JOptionPane.showConfirmDialog(null, "Do you want to remove this Item?", "Confirm",2);
if(confirm==0)
{
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String from = df.format(txtfrom.getDate());
String to = df.format(txtto.getDate());
model.removeRow(row);
core.removeRec(selected,selected2);
tblCompute.setModel(core.lateTotal(from,to));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "error");
}
}
}
这是我以前在数据库中删除的功能,但只能删除1行
public void removeRec(String name, String date) throws Exception
{
Connect();
int i = st.executeUpdate("Delete from tbl_temp where holderName = '"+name+"' AND IODate='"+date+"'");
}
谢谢!
答案 0 :(得分:0)
首先,您需要设置model.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
。
然后使用int[] selectedRows = table.getSelectedRows()
获取所选行的索引。为每一行调用循环中的删除过程。
如果您认为表中会有很多删除,则可以重写删除查询以仅调用sql:因为您正在检查值对(holder_name,io_date),所以没有直接使用预处理语句的方法in (..)
子句,因此您可以像这样在航班上构建查询:
StringBuilder b = new StringBuilder();
b.append("Delete from tbl_temp where ");
for (int i = 0; i < selectedRows.length; i++) {
int row = selectedRows[i];
String name = model.getValueAt(row, 0).toString();
String date = model.getValueAt(row, 1).toString();
b.append("(holderName = '" +name+"' AND IODate='"+date+"')");
if (i < selectedRows.length - 1) {
b.append(" OR "); //omit the last OR
}
}
st.executeUpdate(b.toString());