DELETE FROM其中ID ='用户插入的文字'?

时间:2013-01-04 18:33:40

标签: java mysql sql

我想在Java中将id = user inserted text的MySQL行删除到jTextField中。我知道我需要使用txtGebruikersID.getText();这样的东西,但不确定如何正确组合它们,这样当有人在JTextField(txtGebruikersID)中插入25时,25的值就是25所在的位置:

query = "delete from gebruiker where gebruiker_ID = 25";

我在QueryManager.java中使用的代码:

public void removeGebruiker() {
        String query;
        query = "delete from gebruiker where gebruiker_ID = 25";
        dbmanager.insertQuery(query);
    }

JTextField名为 txtGebruikersID

我在userPanel.java中使用的代码:

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

        WinkelApplication.getInstance().getQueryManager().removeGebruiker();
        JOptionPane.showMessageDialog(null, "Gebruiker is verwijderd", "Gebruiker", JOptionPane.INFORMATION_MESSAGE);
    }

2 个答案:

答案 0 :(得分:3)

你应该做这样的事情。这是使用sqls

的更首选方式
query = "delete from gebruiker where gebruiker_ID = ?";
PreparedStatement st = con.prepareStatement(query); // con is active connection
st.setInt(1,Integer.parseInt(txtGebruikersID.getText()));

What is SQL Injection"

答案 1 :(得分:2)

将函数编辑为以下内容:

public void removeGebruiker(String gebruiker_id) {
    //Some checks here perhaps
    String query;
    query = "delete from gebruiker where gebruiker_ID = " + gebruiker_id;
    dbmanager.insertQuery(query);
}

假设你有一个小组,

WinkelApplication.getInstance().getQueryManager().removeGebruiker(TEXTFIELDNAMEHERE.getText());

如果用户将12放入文本字​​段,则生成的查询将为:

delete from gebruiker where gebruiker_ID = 12

然而,有更好的方法可以做到这一点。准备好的陈述确实更好。如果您确实使用此方法,请务必检查用户的输入。