本文介绍了为什么我们可以使用string.Format来组成sql语句,但还是执行SQLiteCommand,Parameters.add?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在许多教程中看到了使用变量和参数来组成sql语句的内容.
I saw in many tutorial that compose sql statement by using variable and Parameters.Add likt this
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();
}
我们为什么不使用
string.Format("Update Students SET firstName = '{0}', lastName = '{1}...", @firstName, @lastname)
有什么好处吗?
推荐答案
四个原因:
- 避免 SQL注入攻击
- 避免包含真正撇号的字符串出现问题,而无意引起SQL注入攻击(例如,姓氏"O'Reilly" )
- 避免字符串不必要的转换,这可能由于文化原因而导致失败(例如,"1.23"和"1,23"之间的差异取决于您的文化
- 分开保存代码(SQL)和数据(参数)以提高可读性
- 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
还请注意:
- 这不是特定于SQLite的.这是所有数据库的最佳做法.
-
除非变量是关键字,否则不需要使用
@
作为变量的前缀.所以写起来会更惯用:
- 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));
(同上,方法参数声明以...开头,但不是在SQL语句中.)
(Ditto for the method parameter declarations to start with... but not the parametersinside the SQL statement.)
这篇关于为什么我们可以使用string.Format来组成sql语句,但还是执行SQLiteCommand,Parameters.add?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!