Home >Database >Mysql Tutorial >How Can PreparedStatements Protect Java Applications from SQL Injection Attacks?
SQL Injection Prevention in Java Programs
Preventing SQL injection attacks is crucial in Java programs that interact with databases. An SQL injection attack occurs when untrusted input is inserted into an SQL query, allowing attackers to execute malicious code or manipulate data.
Consider the following Java code that inserts data into a database table:
String insert = "INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";
This code is vulnerable to SQL injection attacks because the values are directly interpolated into the query. For example, an attacker could input the following string as the name:
DROP TABLE customer;
This would cause the entire customer table to be deleted.
To prevent this attack, use PreparedStatement. PreparedStatement objects use placeholders for query parameters, which are then filled in later. This separation prevents untrusted input from being directly interpolated into the query.
The following code demonstrates the use of PreparedStatement:
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 code is protected from SQL injection because the values are set separately from the query. Attackers can no longer alter the intent of the query by inserting malicious input.
The above is the detailed content of How Can PreparedStatements Protect Java Applications from SQL Injection Attacks?. For more information, please follow other related articles on the PHP Chinese website!