Passing a boolean type into a bit parameter type in C# and MS SQL Server

走远了吗. 提交于 2019-12-22 07:42:32

问题


I have a C# method that accepts a clientId (int) and hasPaid (boolean) that represents if the client has paid or not. The MS SQL Server stored procedure expects a BIT value (1 or 0) for the @HasPaid parameter yet the method expects a boolean type (true/false) for hasPaid. Will the ADO.NET code take care of converting the boolean to a bit type for SQL Server or do I need to convert the value of hasPaid into a 1 or 0?

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.AddWithValue("@ClientID", clientId);
            sqlCommand.Parameters.AddWithValue("@HasPaid", hasPaid);
            sqlCommand.Connection.Open();
            var rowsAffected = sqlCommand.ExecuteNonQuery();
        }
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/31055135/passing-a-boolean-type-into-a-bit-parameter-type-in-c-sharp-and-ms-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!