用于初始化 SqlDataAdapter 的字符串成为
SqlDataAdapter
CommandText的SelectCommand属性的。
您可以使用以下代码向该命令添加参数
da = new SqlDataAdapter("SELECT * FROM annotations WHERe annotation LIKE @search", _mssqlCon.connection);da.SelectCommand.Parameters.AddWithValue("@search","%" + txtSearch.Text + "%");- 首先,删除参数占位符周围的单引号。
- 其次,直接在AddWithValue的Value参数中添加通配符
您曾经要求使用 AddWithValue ,但请记住,尽管这是一个有用的快捷方式,但也存在许多弊端,并且所有方面都有据可查。
- 第一:我们可以停止使用AddWithValue()吗?作者讨论了 AddWithValue 如何在查询中返回错误结果
- 第二:数据访问代码如何影响数据库性能,其中作者提供了 AddWithValue 的强大性能问题的证据。 __
因此,不带 AddWithValue 并使用Object和Collection
Initializers语法的相同代码可以写为
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)});并且,上述的一种甚至更简化的内衬版本是:
da.SelectCommand.Parameters.Add("@search",SqlDbType.NVarChar,2000).Value = "%" + txtSearch.Text + "%";


