2015-01-08 45 views
0

即時製作java swing項目,連接到我的數據庫並調用所有值爲JTable,在我的框架中,當您單擊Jtable中的一行並單擊刪除按鈕然後值被刪除,但我有一個bug,因爲如果你試圖刪除一個值(例如,如果你刪除數字1),並在jtable中有另一個相同的值(數字1),那麼他們都將刪除在jtable中刪除多行且值相同

我認爲這個問題是在此代碼

public void mouseClicked(MouseEvent arg0) { 
      try { 
       int row = table.getSelectedRow(); 
       String Description = (table.getModel().getValueAt(row, 1)).toString(); 

       String query = "select * from PostNotice where Description='" + Description + "'"; 
       PreparedStatement pst = connection.prepareStatement(query); 

       ResultSet rs = pst.executeQuery(); 

       while (rs.next()) { 
        textArea.setText(rs.getString("Description")); 
       } 

       pst.close(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 

這是刪除

 public void actionPerformed(ActionEvent e) { 


      String query = "Delete from PostNotice where Description =?"; 
      try { 

       PreparedStatement pst = connection.prepareStatement(query); 
       pst.setString(1, textArea.getText()); 
       pst.execute(); 
       JOptionPane.showMessageDialog(null, "Post Deleted"); 

       pst.close(); 

      } catch (Exception ex) 
      { 
       ex.printStackTrace(); 
      } 
      textArea.setText(""); 
      textArea.requestFocus(); 
      refreshtable(); 
     } 

    }); 
+0

哪裏是刪除查詢?或刪除邏輯? –

回答

1

其實你必須保持引用ID(或另一個主鍵)並通過主鍵值刪除記錄。

代碼表示例如Long id類的字段,並從數據庫中存儲ID到外地

textArea.setText(rs.getString("Description")); 
id=rs.getLong("id"); 

然後你可以使用id刪除

String query = "Delete from PostNotice where id=?"; 
... 
pst.setLong(1, id);