我在许多教程中看到,通过使用变量和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
四个原因:
另请注意:
@除非它们是关键字,否则您不需要将变量用作变量的前缀.所以写下来会更加惯用:
command.Parameters.Add(new SQLiteParameter("@lastName", lastName));
Run Code Online (Sandbox Code Playgroud)
(同样,方法参数声明以...开头,但不是 SQL语句中的参数.)
| 归档时间: |
|
| 查看次数: |
14245 次 |
| 最近记录: |