2013-10-07 36 views
-1

嗨,有人能幫我弄清楚我的愚蠢錯誤在哪裏。 我試圖找出在互聯網上,但無法找到最佳解決方案。我有一個jsp和java控制器,我應該可以從數據庫中刪除記錄,以下是我的代碼。任何有助於將承認使用jsp和servlet刪除函數

public void doDel(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, InstantiationException, IllegalAccessException{ 

     try { 
       HttpSession session = request.getSession(true); 
       messageBean mbean = new messageBean(); 
       int id = mbean.getMesId(); 
       String sql; 
       sql = "DELETE * from message where id =?"; 
       Class.forName(driver).newInstance(); 
       conn = DriverManager.getConnection(url); 
       st = conn.createStatement(); 
       ps = conn.prepareStatement(sql); 
       ps.setInt(1, id); 
       ps.executeUpdate(); 
       conn.commit(); 
       conn.close(); 
+0

只需將id連接到字符串。 sql =「Delete * from message where id =」+ id; – JNL

+1

'嗨,有人能幫我弄清楚我的愚蠢的錯誤在哪裏,對不起,我們手中沒有魔法球。什麼是例外?你在期待什麼?當前代碼的行爲如何? –

+0

@JNL由於SQL注入,您在註釋中提到的方法可能是安全問題。 – Bhushan

回答

1

應當有delete後無*,它只是delete from

1

更改您的查詢作爲

sql = "DELETE from message where id =?"; 

或者以其他方式使用語句中使用statement查詢作爲

sql = "DELETE from message where id ="+id; 
Statement st = conn.createStatement(); 
stmt.executeQuery(sql); 

Reference爲刪除查詢

0

有幾點需要注意:

  1. st = conn.createStatement();不需要。因爲你已經在使用PreparedStatement。

    sql = "DELETE from message where id =?"; //不需要的*

  2. conn.commit();只需要如果要設置conn.setAutoCommit(false);

您必須提供錯誤/堆棧跟蹤到:

  • sql = "DELETE * from message where id =?";因爲這可以寫成得到有用的答案。