C#如何防止数据库中出现重复数据?

标签 c#

当用户输入重复数据时,我如何防止“类(class)标题”在数据库中重复?

   SqlConnection cnn = new SqlConnection();
   SqlCommand cmd = new SqlCommand();
   SqlDataAdapter da = new SqlDataAdapter();
   SqlCommandBuilder cb = new SqlCommandBuilder(da);
   DataSet ds = new DataSet();
    cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
    cnn.Open();

    cmd.CommandText = "select * from  Lesson";
    cmd.Connection = cnn;

    da.SelectCommand = cmd;

    da.Fill(ds, "Lesson");


    DataRow drow = ds.Tables["Lesson"].NewRow();

    drow["TopicID"] = DropDownList1.Text;
    drow["LessonTitle"] = TextBox1.Text;
    drow["LessonDate"] = DateTime.Now;
    ds.Tables["Lesson"].Rows.Add(drow);
    da.Update(ds, "Lesson");

最佳答案

这种唯一性应该由数据库强制执行。向您的表添加唯一约束:

CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)

关于C#如何防止数据库中出现重复数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877346/

相关文章:

c# - mysql 函数的正确语法

c# - sql linq之间有什么区别吗

C# : how to - single instance application that accepts new parameters?

c# - 由于内存不足异常,函数评估被禁用

c# - Entity Framework Core 2(代码优先)更新值不起作用

c# - 如何模拟扩展类并实现接口(interface)的对象?

c# - Entity Framework DBContext 数据绑定(bind)问题

c# - 保存来自不同区域的日期时间值 ASP.NET

c# - Winforms 中的 Explorer.exe 浏览网络文件夹

c# - 上传和接收使用 ASP.NET 进行 http 压缩的大文件会给出 "unexpected end of mime multipart stream"