I read through the answers and still felt the need to stress the key point which illuminates the essence of Prepared Statements. Consider two ways to query one's database where user input is involved:
Naive Approach
One concatenates user input with some partial SQL string to generate a SQL statement. In this case the user can embed malicious SQL commands, which will then be sent to the database for execution.
String SQLString = "SELECT * FROM CUSTOMERS WHERE NAME='"+userInput+"'"
For example, malicious user input can lead to SQLString
being equal to "SELECT * FROM CUSTOMERS WHERE NAME='James';DROP TABLE CUSTOMERS;'
Due to the malicious user, SQLString
contains 2 statements, where the 2nd one ("DROP TABLE CUSTOMERS"
) will cause harm.
Prepared Statements
In this case, due to the separation of the query & data, the user input is never treated as a SQL statement, and thus is never executed. It is for this reason, that any malicious SQL code injected would cause no harm. So the "DROP TABLE CUSTOMERS"
would never be executed in the case above.
In a nutshell, with prepared statements malicious code introduced via user input will not be executed!