SqlCommand.Parameters 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
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);
}
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
備註
Microsoft .NET Framework for SQL Server Data Provider 不支援用來傳入參數給 SQL 語句或由 CommandType.Text 指令呼叫的儲存程序的問號(?)佔位符。 此時必須使用命名參數。 例如:
選擇 * 從客戶中 其中 CustomerID = @CustomerID
Note
若集合中的參數與要執行查詢的需求不符,可能會發生錯誤。
更多資訊請參閱 參數配置。