prepared statements - are they necessary

后端 未结 2 805
有刺的猬
有刺的猬 2020-12-03 20:08

Prepared statments add a significant amount of code...yet I keep hearing mentions to use them...what value is added by going from 1 line of code to about 6? Is this simply

2条回答
  •  长情又很酷
    2020-12-03 20:41

    It's not fair to say that prepared statements cause 1 line of code to explode to 6. Actually, to use one you need just 2 lines: one to prepare the statement, and one to bind the parameters. Any other code you write (execute query, bind results, fetch results, etc.) would also be needed even if you didn't use prepared statements.

    So in essence we are talking about what one additional line of code buys you. It buys you two things:

    1. Protection against sql injections (which also includes protection against non-malicious malformed queries, e.g. preventing your query from breaking if an injected variable contains a single quote)
    2. Possible performance benefits, if you end up executing the same prepared statement for different injected values.

    Point #2 may not always apply, but consider that point #1 also saves you the necessary trouble of manually escaping the values to be injected in your query. This would be additional code (even if you can do it inline on the same line) that you would need to write yourself if not using prepared statements.

    As I see things, we can conclude that with prepared statements you end up getting security and possibly performance for free.

提交回复
热议问题