I have to add a statement to my java program to update the database table:
String insert = "INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";
I've heard this can be exploited via SQL injection, for example:
DROP TABLE customer;
My program has a Java GUI and all name, address and email values are retrieved from Jtextfields
. I would like to know how to add the following code (DROP TABLE customer;
) to my insert statement and how to prevent this.
P粉1949190822023-10-21 12:11:28
For example:
name = "'); DROP TABLE customer; --"
will insert this value into insert:
INSERT INTO customer(name,address,email) VALUES(''); DROP TABLE customer; --"','"+addre+"','"+email+"');
Using prepared statements and SQL parameters ("steal" example from Matt Fellows):
String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);"; PreparedStament ps = connection.prepareStatment(insert);
Also parse the values of such variables and ensure that they do not contain any disallowed characters (such as ";" in the name).
P粉0304790542023-10-21 09:25:32
You need to use PreparedStatement. For example
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 a hacker puts this in is if the string you insert comes from an input somewhere - like an input field on a web page, or an input field on a form in an app or similar.