加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么我们做SQLiteCommand,Parameters.add,而我们可以使

发布时间:2020-12-15 06:25:42 所属栏目:百科 来源:网络整理
导读:我在许多教程中看到,通过使用变量和Parameters.Add来构造sql语句 public void updateStudent(String @studentID,String @firstName,String @lastName){ SQLiteCommand command = conn.CreateCommand(); command.CommandText = "UPDATE Students SET firstNam
我在许多教程中看到,通过使用变量和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();
}

为什么我们不用

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

任何好处?

解决方法

四个原因:

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

另请注意:

>这不是SQLite特定的.这是所有数据库的最佳做法.
>除非是关键字,否则不需要使用@作为变量的前缀.所以写一下更惯用语:

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

(同上方法参数声明以…开头但不是参数在SQL语句里面)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读