You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET与C#中新增代金券数据库记录前校验DiscountCode是否存在的实现方法

在ASP.NET中插入代金券前检查DiscountCode是否重复

嘿,刚接触ASP.NET和C#不用慌,这个检查重复的需求其实很常见,咱们一步步来搞定它~

首先,核心思路是在执行插入操作前,先查询数据库里是否已经存在相同的DiscountCode,如果存在就不执行插入,反之再插入新记录。另外还要注意代码的健壮性,比如用using语句自动管理数据库连接,避免忘记关闭连接导致的问题。

第一步:添加检查DiscountCode是否存在的方法

先写一个单独的方法来做检查,用EXISTS语句比COUNT(*)更高效,因为找到匹配项就会停止查询:

public bool IsDiscountCodeExists(string discountCode)
{
    string queryStr = "SELECT EXISTS(SELECT 1 FROM Voucher WHERE DiscountCode = @Code)";
    using (SqlConnection conn = new SqlConnection(_connStr))
    {
        using (SqlCommand cmd = new SqlCommand(queryStr, conn))
        {
            cmd.Parameters.AddWithValue("@Code", discountCode);
            conn.Open();
            // 执行查询并将结果转为bool类型
            return (bool)cmd.ExecuteScalar();
        }
    }
}

第二步:修改你的插入方法

在原来的VoucherInsert方法里,先调用上面的检查方法,如果返回true说明代码已存在,直接返回0(或者抛出自定义异常提示用户);如果不存在再执行插入操作:

public int VoucherInsert()
{
    // 先检查DiscountCode是否存在
    if (IsDiscountCodeExists(this.Code))
    {
        // 代码已存在,返回0表示插入失败,也可以抛出异常提示用户
        return 0;
    }

    int result = 0;
    string queryStr = "INSERT INTO Voucher(VoucherName,VoucherDescription,DiscountAmount,DiscountCode)" + 
                      " values (@Name,@Description,@Amount,@Code)";
    
    // 用using语句自动释放连接和命令资源,不用手动Close
    using (SqlConnection conn = new SqlConnection(_connStr))
    {
        using (SqlCommand cmd = new SqlCommand(queryStr, conn))
        {
            cmd.Parameters.AddWithValue("@Name", this.Name);
            cmd.Parameters.AddWithValue("@Description", this.Description);
            cmd.Parameters.AddWithValue("@Amount", this.Amount);
            cmd.Parameters.AddWithValue("@Code", this.Code);
            conn.Open();
            result = cmd.ExecuteNonQuery();
        }
    }
    return result;
}

额外的安全保障:数据库层面加唯一约束

为了避免极端情况下的并发问题(比如两个请求同时检查到代码不存在,然后同时插入),建议直接在数据库的Voucher表中给DiscountCode列添加唯一约束,这样即使代码层面没拦住,数据库也会抛出重复键的异常,保证数据的唯一性。

比如在SQL Server中执行这个语句:

ALTER TABLE Voucher
ADD CONSTRAINT UQ_Voucher_DiscountCode UNIQUE (DiscountCode);

这样当有重复代码插入时,数据库会抛出异常,你可以在代码里捕获这个异常,给用户更友好的提示。

内容的提问来源于stack exchange,提问作者Kah Hao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:17:43