基于jcomboBox从数据库中删除数据会引发错误

时间:2014-04-04 19:31:47

标签: java sql jdbc sql-delete

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)     
{                                         

    Connection conn=DbCon.conDB();
    //String Mname =jComboBox1.getSelectedItem().toString();
    String sql="delete Name from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";
    try{

        pst=conn.prepareStatement(sql);
     //   pst.executeQuery();
        pst.executeUpdate(sql);
        JOptionPane.showMessageDialog(null,"Movie Deleted Sucessfully");
    }

   catch(SQLException e)
   {
   JOptionPane.showMessageDialog(null, e);
   }

}

1 个答案:

答案 0 :(得分:1)

2个问题:

  1. 一般来说,DELETE的语法是

    String sql = "delete from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";

  2. PreparedStatement不使用SQL字符串,即只使用pst.executeUpdate()

  3. 附注:由于您已经在使用PreparedStatement,因此您可以使用占位符来避免SQL injection次攻击,而不是使用String级联。

    String sql = "delete from nowshowingmovie where Name = ?";
    pst.setString(1, jComboBox1.getSelectedItem().toString());
    pst.executeUpdate();