I have to add a statement to my java program to update a database table:
String insert = "INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";
I heard that this can be exploited through an SQL injection like:
DROP TABLE customer;
My program has a Java GUI and all name, address and email values are retrieved from Jtextfields
. I want to know how the following code (DROP TABLE customer;
) could be added to my insert statement by a hacker and how I can prevent this.
Advertisement
Answer
You need to use PreparedStatement. e.g.
String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);"; PreparedStatement ps = connection.prepareStatement(insert); ps.setString(1, name); ps.setString(2, addre); ps.setString(3, email); ResultSet rs = ps.executeQuery();
This will prevent injection attacks.
The way the hacker puts it in there is if the String you are inserting has come from input somewhere – e.g. an input field on a web page, or an input field on a form in an application or similar.