Leggere in inglese

Condividi tramite


SqlParameterCollection.AddWithValue(String, Object) Metodo

Definizione

Aggiunge un valore alla fine del SqlParameterCollection.

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

Parametri

parameterName
String

Nome del parametro.

value
Object

Valore da aggiungere. Usare Value anziché null per indicare un valore Null.

Restituisce

Oggetto SqlParameter.

Esempio

Nell'esempio seguente viene illustrato come usare il metodo AddWithValue.

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

Commenti

AddWithValue sostituisce il metodo SqlParameterCollection.Add che accetta un String e un Object. L'overload di Add che accetta una stringa e un oggetto è stato deprecato a causa di possibili ambiguità con l'overload SqlParameterCollection.Add che accetta un String e un valore di enumerazione SqlDbType in cui il passaggio di un numero intero con la stringa può essere interpretato come il valore del parametro o il valore SqlDbType corrispondente. Usare AddWithValue ogni volta che si desidera aggiungere un parametro specificandone il nome e il valore.

Per SqlDbTypeXml valori di enumerazione, è possibile utilizzare una stringa, un valore XML, un XmlReader'istanza del tipo derivato o un oggetto SqlXml.

Si applica a

Prodotto Versioni
.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)

Vedi anche