Preventing SQL injection attacks in Java programs
P粉328911308
P粉328911308 2023-10-20 20:06:17
0
2
584

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 fromJtextfields. I would like to know how to add the following code (DROP TABLE customer;) to my insert statement and how to prevent this.

P粉328911308
P粉328911308

reply all (2)
P粉194919082

For example:

name = "'); DROP TABLE customer; --"

will insert this value intoinsert:

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粉030479054

    You need to usePreparedStatement. 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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!