C#中的SqlDataAdapter使用Parameters.AddWithValue [英] c# Using Parameters.AddWithValue in SqlDataAdapter

查看:1593
本文介绍了C#中的SqlDataAdapter使用Parameters.AddWithValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用Parameters.Add.WithValue在SqlDataAdapter的。下面搜索codeS。

How can i use Parameters.Add.WithValue in SqlDataAdapter. Below searching codes.

var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);

我重写了code是这样的:

I rewrote the code like this:

SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%@search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("@search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);

但失败了。你能帮我哪里是我的错吗?
您真诚的。

But failed. Could you help me where is my fault?
Yours sincerely.

推荐答案

用于初始化字符串的SqlDataAdapter 变成了的CommandText 的<一个href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx">SelectCommand该SqlDataAdapter的财产。
你可以使用这个code参数添加到该命令

The string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter.
You could add parameters to that command with this code

da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE @search",
                        _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("@search","%" + txtSearch.Text + "%");

  • 首先,去掉周围的参数占位符的单引号。
  • 二,直接的价值参数添加通配符 AddWithValue
    • First, remove the single quote around the parameter placeholder.
    • Second, add the wildcard character directly in the Value parameter of AddWithValue
    • 您已经要求使用 AddWithValue ,但请记住,虽然它是一个有用的快捷方式,也有许多缺点和所有有据可查的。

      You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.

      • First: Can we stop using AddWithValue() already? where the author discuss how AddWithValue could give back wrong results in your queries
      • Second: How Data Access Code Affects Database Performance where the author presents evidences of strong performance problems for AddWithValue

      所以,没有 AddWithValue 并使用对象相同的code和集合初始化语法可以写成

      So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as

      da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE @search",
                              _mssqlCon.connection);
      da.SelectCommand.Parameters.Add(new SqlParameter
      {
          ParameterName = "@search",
          Value = "%" + txtSearch.Text + "%",
          SqlDbType = SqlDbType.NVarChar,
          Size = 2000  // Assuming a 2000 char size of the field annotation (-1 for MAX)
      });
      

      这篇关于C#中的SqlDataAdapter使用Parameters.AddWithValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆