多条件查询 VS 参数化查询

一直以来对参数化查询有个误解:SqlCommand对象中,给Parameters添加参数的个数必须和CommandText中使用的变量个数相等。今天测试发现:

·CommandText中使用的变量在Parameters中必须有对应的参数;
·Parameters中参数的个数可以多于CommandText中使用的变量个数;

道理很简单,你在程序中使用的变量都必须先声明,但声明的变量没有要求说一定都得在程序中使用。

/// <summary>
/// 产品搜索
/// </summary>
/// <param name="productName">产品名称</param>
/// <param name="categoryID">产品分类ID,-1时忽略</param>
/// <returns></returns>
private DataTable List(string productName, int categoryID)
{
    DataTable table = new DataTable();

    try
    {
        using (SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Northwind;user id=sa;password=sa"))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;

                if (categoryID == -1)
                    cmd.CommandText = "select * from Products where ProductName=@ProductName";
                else
                    cmd.CommandText = "select * from Products where ProductName=@ProductName and CategoryID=@CategoryID";

                cmd.CommandType = CommandType.Text;
                cmd.CommandTimeout = 100;

                SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@ProductName", SqlDbType.NVarChar),
                    new SqlParameter("@CategoryID", SqlDbType.Int)
                };
                parms[0].Value = productName;
                parms[1].Value = categoryID;

                for (int i = 0; i < parms.Length; i++)
                    cmd.Parameters.Add(parms[i]);

                using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                {
                    adapter.Fill(table);
                }
            }
        }
    }
    catch { }

    return table;
}

上边例子中,当categoryID=-1时,声明的@CategoryID变量就是多余的,但并不影响程序运行,这样在多条件查询下使用参数化查询写代码就简单多了。

评论: 0 | 引用: 0 | 查看次数: 4959
发表评论
登录后再发表评论!