PreparedStatement在Java中删除

时间:2012-03-08 18:30:20

标签: java prepared-statement

我编写了一个代码,用于从我的Java程序中删除MySQL数据库中的记录。它成功编译并运行它,但记录仍在数据库中。有什么建议吗?

JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent arg0) {

        try {

            Object[] options = {"Yes", "No"};
            Component form = null;
            int n = JOptionPane.showOptionDialog(form, "Do you like to delete the record for Student ID: " +
                    textField_16.getText() + " ?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);

            if(n == JOptionPane.YES_OPTION) {

                String mock = textField_16.getText();   

                String sql = "DELETE FROM mockexam WHERE MockID =?";
                PreparedStatement prest = con.prepareStatement(sql);
                prest.setString(1, mock);
                int val = prest.executeUpdate();
                JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
            }
        } 
        catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
        }       
    }
});

btnDelete.setBounds(45, 235, 89, 23);
panel_1.add(btnDelete);

3 个答案:

答案 0 :(得分:3)

您没有指明您正在运行哪种类型的数据库(innoDB或MyISAM等),但如果您针对InnoDB运行,则需要commit()语句在{executeUpdate()之后提交事务。 1}}。您可能在日志中有一些内容表明您的事务已被回滚。

try {
    Object[] options = {"Yes", "No"};
    Component form = null;
    int n = JOptionPane.showOptionDialog(form, 
            "Do you like to delete the record for Student ID: " + textField_16.getText() + " ?", 
            "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);

    if(n == JOptionPane.YES_OPTION) {
        String sql = "DELETE FROM mockexam WHERE MockID =?";
        PreparedStatement prest = con.prepareStatement(sql);
        prest.setString(1, "MockID");
        prest.executeUpdate();
        con.commit();
        JOptionPane.showMessageDialog(frmDeleteMock, "The record has been deleted successfully.");
    }
} 

catch (SQLException e) {
    e.printStackTrace();
    JOptionPane.showMessageDialog(frmDeleteMock, "Record couldn't be deleted. Please try again.");
}

您还错过了close()块中的PreparedStatement finally{}调用的连接,以确保您的代码中没有任何泄漏。

答案 1 :(得分:2)

prest.setString(1, "MockID");

您正在寻找等于MockID的MockID我假设您要删除具有特定ID使用的条目:

String mockID = "2"; //Set this however you want to set it.
prest.setString(1, mockID);
int val = prest.executeUpdate();
//Check val for what happened.

答案 2 :(得分:0)

如果没有符合您条件的记录,那么SQL将被认为有效。因此我对这个参数持怀疑态度。数据库中列的类型是什么?它可能是一个固定的长度值,所以不匹配“MockID”?