为什么我们在使用string.Format来编写sql语句的同时执行SQLiteCommand,Parameters.add?

Sup*_*ENG 15 c# sqlite

我在许多教程中看到,通过使用变量和Parameters.Add来构造sql语句

public void updateStudent(String @studentID, String @firstName, String @lastName)
{
    SQLiteCommand command = conn.CreateCommand();
    command.CommandText = "UPDATE Students SET firstName = @firstName, lastName = @lastName WHERE studentID = @studentID";
    command.Parameters.Add(new SQLiteParameter("@studentID", @studentID));
    command.Parameters.Add(new SQLiteParameter("@firstName", @firstName));
    command.Parameters.Add(new SQLiteParameter("@lastName" , @lastName));
    command.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)

我们为什么不用

string.Format("Update Students SET firstName = '{0}', lastName = '{1}...", @firstName, @lastname)
Run Code Online (Sandbox Code Playgroud)

任何好处?

Jon*_*eet 36

四个原因:

  • 避免SQL注入攻击
  • 避免使用包含真正撇号的字符串的问题而不打算引起SQL注入攻击(例如"O'Reilly"的姓氏)
  • 避免字符串不必要的转换,这可能会因文化原因导致失败(例如"1.23"和"1,23"之间的差异取决于您的文化
  • 保持代码(SQL)和数据(参数)分开以获得更清晰的可读性

另请注意:

  • 这不是特定于SQLite的.这是所有数据库的最佳实践.
  • @除非它们是关键字,否则您不需要将变量用作变量的前缀.所以写下来会更加惯用:

    command.Parameters.Add(new SQLiteParameter("@lastName", lastName));
    
    Run Code Online (Sandbox Code Playgroud)

    (同样,方法参数声明以...开头,但不是 SQL语句中的参数.)