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.
For example:
will insert this value into insert:
Using prepared statements and SQL parameters ("steal" example from Matt Fellows):
Also parse the values of such variables and ensure that they do not contain any disallowed characters (such as ";" in the name).
You need to use PreparedStatement. For example
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.