更新时间:2021-12-07 22:10:29
使用SQL参数时,我发现 AddWithValue
的类型的自动检测功能不太可靠。我发现***只调用 Add
一个显式设置类型, Add
也会返回它从函数调用,这样您就可以随后调用 .Value
。
When working with SQL parameters I find AddWithValue
's auto detection feature of the type too unreliable. I find it better to just call Add
a explicitly set the type, Add
also returns the new parameter it creates from the function call so you can just call .Value
on it afterward.
public void UpdateClient(int clientId, bool hasPaid)
{
using (SqlConnection conn = new SqlConnection(this.myConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand("uspUpdatePaymentStatus", conn))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@ClientID", SqlDbType.Int).Value = clientId;
sqlCommand.Parameters.Add("@HasPaid", SqlDbType.Bit).Value = hasPaid;
sqlCommand.Connection.Open();
var rowsAffected = sqlCommand.ExecuteNonQuery();
}
}
}
使用正确的类型是双重的在使用存储过程并且期望使用特定类型时很重要,我只是养成了始终以这种方式进行操作的习惯。
Using the correct type is doubly important when using stored procedures and it is expecting a specific type, I just got in to the habit of always doing it this way.