共用方式為


SqlParameterCollection.AddWithValue(String, Object) 方法

定義

將值加入至 SqlParameterCollection 結尾。

public:
 Microsoft::Data::SqlClient::SqlParameter ^ AddWithValue(System::String ^ parameterName, System::Object ^ value);
public Microsoft.Data.SqlClient.SqlParameter AddWithValue (string parameterName, object value);
member this.AddWithValue : string * obj -> Microsoft.Data.SqlClient.SqlParameter
Public Function AddWithValue (parameterName As String, value As Object) As SqlParameter

參數

parameterName
String

參數名稱。

value
Object

要加入的值。 使用Value而非 null,表示 null 值。

傳回

SqlParameter 物件。

範例

下列範例示範如何使用 AddWithValue 方法。

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);
            }
        }
    }

備註

AddWithValueSqlParameterCollection.Add取代接受 StringObject 的方法。 接受字串和 物件的多載已被取代,因為多 String 載的可能模棱兩可 SqlParameterCollection.Add ,採用 的 多載 AddSqlDbType 列舉值,其中傳遞具有字串的整數可以解譯為參數值或對應的 SqlDbType 值。 只要您想要指定參數的名稱和值,即可 AddWithValue 使用 。

針對 SqlDbTypeXml 列舉值,您可以使用字串、XML 值、 XmlReader 衍生型別實例或 SqlXml 物件。

適用於