How can prepared statements protect from SQL injection attacks?

前端 未结 9 2069
予麋鹿
予麋鹿 2020-11-21 05:40

How do prepared statements help us prevent SQL injection attacks?

Wikipedia says:

Prepared statements are resilient against SQL injection, because

9条回答
  •  梦谈多话
    2020-11-21 06:01

    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!

提交回复
热议问题