1

当用户输入重复数据时,我将如何防止“课程标题”在数据库中重复?

   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");
4

2 回答 2

4

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

CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
于 2013-11-09T15:26:45.003 回答
1

您可以创建一个函数来检查重复的LessonTitle.

说明:这里我创建了一个名为checkDuplicateTitle().

此函数将 LessonTable 的 AllRows 作为 DataRowCollection 并LessonTitle作为输入进行验证。

它将检查LessonTitle每一行。如果给定LessonTitle与表中的现有标题匹配,则此函数返回 true,否则返回 false。

如果返回值为 true,我们将忽略使用LessonTitle已经存在的新行更新表,否则我们将添加它。

代码如下:

void UpdateLessonTable()
{
     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");

     if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
        {
        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");
        }
       else
        {
         //you can display some warning here
         // MessageBox.Show("Duplicate Lesson Title!");
        }
}

//function for checking duplicate LessonTitle

bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
        {
            foreach (DataRow row in rowTitle)
            {
               if(row["LessonTitle"].Equals(newTitle))
                return true;
            }
            return false;
        }
于 2013-11-09T15:32:10.063 回答