SqlCommand.Parameters的使用

   在c#中执行sql语句时,避免会遇到传参的问题。Parameters就是用来做参数化查询,不然很容易被黑客拿到数据。

 一、简介

  引用自:https://msdn.microsoft.com/ZH-CN/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx

  命名空间:   System.Data.SqlClient
  程序集:  System.Data(位于 System.Data.dll)

  语法

  public SqlParameterCollection Parameters { get; }

  属性值

  Type: System.Data.SqlClient.SqlParameterCollection

  Transact-SQL 语句或存储过程的参数。 默认值为空集合。

 二、示例

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

 

   三、常见用法

  1. 分页查询

   如下定义, 如果在查询数据语句和查询总条数中使用,会在第二处提示被引用的异常

List<SqlParameter> parameters = new List<SqlParameter>()  ;

  解决方法:

 parameters.Select(x => ((ICloneable)x).Clone()).ToArray<object>()

  2. Like的用法

  原因是传入的参数会被自动加上单引号,直接使用 Title like '%@Title%'会出错

if (!string.IsNullOrEmpty(Title))
{ 
    keyCondition += " and (Title like @Title ) ";
    parameters.Add(new SqlParameter() { ParameterName = "@Title", Value = "%" + Title + "%" });
}

 

  

 

posted @ 2018-01-12 13:06  心存善念  阅读(8072)  评论(0编辑  收藏  举报