2013-10-07 37 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 =?";因为这可以写成得到有用的答案。