无法处理与 CHECK 贡献相关的 sql 异常

本文关键字:sql 异常 处理 CHECK | 更新日期: 2023-09-27 17:56:33

我正在使用C#win表单和MSSQL服务器编写桌面应用程序。 在我的数据库中,我有一个这样的表:

create table material(
id int identity(700,3),
materialName nvarchar(100) not null default (0),
unitPrice decimal(19,2) not null default (0),
carbohydrate tinyint not null default (0),
protein tinyint not null default (0),
fat tinyint not null default (0),
humidity tinyint not null default (0) ,
minerals tinyint not null default (0),
constraint PK_id_materialPriceAndStandard primary key (id),
constraint UQ_materialName_materialPriceAndStandard unique (materialName), 
constraint CHECK_totlaMineralAmount check 
(carbohydrate + protein + fat + humidity + minerals =100 )) 

材料表中5个字段的总数不得超过100个。

在 C# 中,当用户输入超过 100 的金额时,我会收到此异常:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: The INSERT statement conflicted with the CHECK constraint         
"CHECK_totalMineralAmount_materialPrice".
The conflict occurred in database "secaloFormula", table "dbo.materialPrice"

这是连接到数据库并调用存储过程的代码:

public void addMaterial()
    {
        string ConString = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString(); 
        using(SqlConnection sqlCon = new SqlConnection(ConString))
        using(SqlCommand sqlCmd = new SqlCommand("spAddMaterial",sqlCon))
        {
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("materialName", MaterialName); 
            sqlCmd.Parameters.AddWithValue("unitPrice",Price);
            sqlCmd.Parameters.AddWithValue("carbohydrate",Carbohydrtate);
            sqlCmd.Parameters.AddWithValue("proterin", Proterin); 
            sqlCmd.Parameters.AddWithValue("fat",Fat); 
            sqlCmd.Parameters.AddWithValue("humidity", Humadity); 
            sqlCmd.Parameters.AddWithValue("minerals",Minerlas);
            sqlCon.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCon.Close();
            sqlCon.Dispose(); 
        }
    }

如何处理此异常,以便在插入金额超过 100 时提醒用户?

无法处理与 CHECK 贡献相关的 sql 异常

try 
{
   sqlCmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
   // the error should be in the Ex
}

SqlException 类

请参阅链接。
这个错误可能在 ex.错误。

使用我认为你不需要处理,但我怀疑它会伤害任何东西

我建议检查业务逻辑中的约束,而不是依赖数据库来拒绝任何无效消息。如果您死心塌地地使用业务规则的约束,则可以尝试/捕获 ExecuteNonQuery 并返回引发的异常。