SqlCommand.Parameters 属性

定义

public:
 property Microsoft::Data::SqlClient::SqlParameterCollection ^ Parameters { Microsoft::Data::SqlClient::SqlParameterCollection ^ get(); };
public Microsoft.Data.SqlClient.SqlParameterCollection Parameters { get; }
member this.Parameters : Microsoft.Data.SqlClient.SqlParameterCollection
Public ReadOnly Property Parameters As SqlParameterCollection

属性值

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

示例

以下示例演示如何创建 SqlCommand 并将参数添加到 SqlParameterCollection

using System;
using System.Data;
using Microsoft.Data.SqlClient;


class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        string demo = @"<StoreSurvey xmlns=""http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey""><AnnualSales>1500000</AnnualSales><AnnualRevenue>150000</AnnualRevenue><BankName>Primary International</BankName><BusinessType>OS</BusinessType><YearOpened>1974</YearOpened><Specialty>Road</Specialty><SquareFeet>38000</SquareFeet><Brands>3</Brands><Internet>DSL</Internet><NumberEmployees>40</NumberEmployees></StoreSurvey>";
        Int32 id = 3;
        UpdateDemographics(id, demo, connectionString);
        Console.ReadLine();
    }
    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);
            }
        }
    }

注解

Microsoft .NET Framework Data Provider for SQL Server 不支持使用问号 (?) 占位符将参数传递给 SQL 语句或由 命令调用的CommandType.Text存储过程。 在这种情况下,必须使用命名参数。 例如:

SELECT * FROM Customers WHERE CustomerID = @CustomerID

注意

如果集合中的参数与要执行的查询的要求不匹配,则可能会导致错误。

有关详细信息,请参阅 配置参数

适用于