将布尔类型传递到C#和MS SQL Server中的位参数类型

web*_*orm 5 c# sql-server ado.net

我有一个C#方法接受clientId(int)和hasPaid(boolean),表示客户端是否已付款.MS SQL Server存储过程需要@HasPaid参数的BIT值(1或0),但该方法需要hasPaid的boolean类型(true/false).ADO.NET代码是否会将转换为SQL Server booleanbit类型,还是需要将值hasPaid转换为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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 10

使用SQL参数时,我发现AddWithValue该类型的自动检测功能太不可靠.我发现最好只调用Add一个显式设置类型,Add也返回它从函数调用创建的新参数,这样你就可以.Value在之后调用它.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用正确的类型在使用存储过程时非常重要,并且它期望特定类型,我只是养成了这样做的习惯.

  • a Bit 是 0 或 1,但如果您这样做: sqlCommand.Parameters.Add("@HasPaid", SqlDbType.Bit).Value = 1; 执行时会出现错误。 (2认同)