简体   繁体   中英

DELETE FROM where ID = 'user inserted text'?

I want to delete MySQL rows where id = user inserted text into jTextField in Java. I know I need to use something like txtGebruikersID.getText(); but not sure how to combine them correctly so that when someone inserts like 25 in JTextField (txtGebruikersID) that value of 25 goes where the 25 is in:

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

Code I use in QueryManager.java:

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

JTextField is called txtGebruikersID

And code I use in userPanel.java:

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

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

You should do something like this. This is more preferred way on working with 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"

Edit the function to something like this:

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

Assuming you have a panel,

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

If the user puts 12 into the textfield the resulting query will be:

delete from gebruiker where gebruiker_ID = 12

Nevertheless there are better ways to do this. Prepared statements are indeed better. If you do use this method make sure to check the input from the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM