Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a PreparedStatement avoid or prevent SQL injection?

I know that PreparedStatements avoid/prevent SQL Injection. How does it do that? Will the final form query that is constructed using PreparedStatements be a string or otherwise?

like image 936
Prabhu R Avatar asked Oct 17 '09 12:10

Prabhu R


People also ask

How does prepared statements prevent SQL injection?

PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters. PreparedStatement allows us to execute dynamic queries with parameter inputs. PreparedStatement provides different types of setter methods to set the input parameters for the query.

Why are prepared statements more secure?

Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.

What do prepared statements do?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database.

What is the best defense against SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.


1 Answers

Consider two ways of doing the same thing:

PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')"); stmt.execute(); 

Or

PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)"); stmt.setString(1, user); stmt.execute(); 

If "user" came from user input and the user input was

Robert'); DROP TABLE students; -- 

Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.

like image 66
Paul Tomblin Avatar answered Sep 23 '22 02:09

Paul Tomblin