2011-02-13 127 views
1

我想從我的表中刪除一個事件。然而,我似乎無法讓它工作。 我的SQL語句是:刪除sql不刪除

public void deleteEvent(String eventName){ 
    String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1"; 
    db.update(query); 
    System.out.println (query); 
} 

使用MySQL數據庫

+3

什麼是`db`和`update`做了什麼,我不知道,但我確定如果您閱讀以下內容:http://oreilly.com/catalog/javadata/chapter/ch04.html,並正確編寫您的查詢,您將獲得期望的結果。 – AlexanderMP 2011-02-13 12:06:24

回答

4

嘗試使用以下:

String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1"; 

     try { 
      Connection con = getConnection(); 
      Statement s = con.createStatement(); 

      s.execute(query); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 

你必須編寫你的getConnection()方法返回一個有效的數據庫連接。

0

我建議使用Statement.executeUpdate方法,因爲它返回一個整數。因此,在執行此刪除查詢之後,如果確實刪除了任何記錄(在這種情況下,由於您使用的是LIMIT = 1,您會希望此方法返回1),因此您也將獲得有關信息。我還建議一旦你不需要它就關閉語句,這裏是框架實現:

private void performDelete(Connection conn, String deleteQuery, int expectedResult) throws SQLException { 
    Statement stmt = conn.createStatement(); 
    int result = -1; 
    try { 
     result = stmt.executeUpdate(deleteQuery); 
     if(result != expectedResult) { 
      //Here you can check the result. Perhaps you don't need this part 
      throw new IllegalStateException("Develete query did not return expected value"); 
     } 
    } catch(SQLException e) { 
     //Good practice if you use loggers - log it here and rethrow upper. 
     //Or perhaps you don't need to bother in upper layer if the operation 
     //was successful or not - in such case, just log it and thats it. 
     throw e; 
    } finally { 
     //This should be always used in conjunction with ReultSets. 
     //It is not 100% necessary here, but it will not hurt 
     stmt.close(); 
    } 
}