Why we do SQLiteCommand, Parameters.add while we can use string.Format to compose sql statement?

后端 未结 1 421
你的背包
你的背包 2021-01-11 09:36

I saw in many tutorial that compose sql statement by using variable and Parameters.Add likt this

public void updateStudent(String @studentID, String @firstNa         


        
相关标签:
1条回答
  • 2021-01-11 10:07

    Four reasons:

    • Avoiding SQL injection attacks
    • Avoiding problems with strings containing genuine apostrophes with no intention of causing a SQL injection attack (e.g. a last name of "O'Reilly"
    • Avoiding string unnecessary conversions, which can cause failures for cultural reasons (e.g. the difference between "1.23" and "1,23" depending on your culture
    • Keeping the code (SQL) and the data (parameters) separate for cleaner readability

    Also note:

    • This isn't SQLite specific. It's best practice for all databases.
    • You don't need to use @ as a prefix to your variables unless they're keywords. So it would be more idiomatic to write:

      command.Parameters.Add(new SQLiteParameter("@lastName", lastName));
      

      (Ditto for the method parameter declarations to start with... but not the parameters inside the SQL statement.)

    0 讨论(0)
提交回复
热议问题