SqlParameterCollection.AddWithValue(String, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
會為 的末尾 SqlParameterCollection加上一個值。
public:
System::Data::SqlClient::SqlParameter ^ AddWithValue(System::String ^ parameterName, System::Object ^ value);
public System.Data.SqlClient.SqlParameter AddWithValue(string parameterName, object value);
member this.AddWithValue : string * obj -> System.Data.SqlClient.SqlParameter
Public Function AddWithValue (parameterName As String, value As Object) As SqlParameter
參數
- parameterName
- String
參數的名稱。
傳回
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);
}
}
}
Private Sub UpdateDemographics(ByVal customerID As Integer, _
ByVal demoXml As String, _
ByVal connectionString As String)
' Update the demographics for a store, which is stored
' in an xml column.
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = @demographics " _
& "WHERE CustomerID = @ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
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()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
End Sub
備註
AddWithValue 取代 SqlParameterCollection.Add 了取 a String 和 的 Object。 該超載Add會取一個字串和一個物件,因為可能存在SqlDbTypeSqlParameterCollection.AddString歧義,將一個與列舉值一起傳遞整數,可能被解讀為參數值或對應SqlDbType值。 只要你想新增參數,就指定 AddWithValue 名稱和值。
列 SqlDbTypeXml 舉值可以用字串、XML 值、 XmlReader 派生型別實例或 SqlXml 物件。