英語で読む

次の方法で共有


SqlParameterCollection.AddWithValue(String, Object) メソッド

定義

SqlParameterCollectionの末尾に値を追加します。

public System.Data.SqlClient.SqlParameter AddWithValue(string parameterName, object value);

パラメーター

parameterName
String

パラメーターの名前。

value
Object

追加する値。 null 値を示すには、null ではなく Value を使用します。

戻り値

SqlParameter オブジェクト。

次の例では、AddWithValue メソッドの使用方法を示します。

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

注釈

AddWithValue は、StringObjectを受け取る SqlParameterCollection.Add メソッドを置き換えます。 文字列を受け取り、オブジェクトを受け取る Add のオーバーロードは、String を受け取る SqlParameterCollection.Add オーバーロードと SqlDbType 列挙値とのあいまいさが考えられるため非推奨となりました。この場合、文字列を使用して整数を渡すことは、パラメーター値または対応する SqlDbType 値のいずれかと解釈できます。 パラメーターの名前と値を指定してパラメーターを追加する場合は常に、AddWithValue を使用します。

SqlDbType Xml 列挙値には、文字列、XML 値、XmlReader 派生型インスタンス、または SqlXml オブジェクトを使用できます。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, 6 (package-provided), 7 (package-provided), 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)

こちらもご覧ください