2013-11-09 205 views
0

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

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"); 
+1

通过第一选择,并检查是否字符串已经存在,如果没有,插入,如果它存在,什么也不做。 – Max

+3

您也可以通过直接在数据库中对表列使用唯一约束来防止重复。以下是它的方式:http://technet.microsoft.com/en-us/library/ms190024.aspx –

+0

你能提供一些例子吗?我是新来的,谢谢。 – Nian

回答

0

您可以创建一个函数来检查重复的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; 
     } 
+0

当他必须从数据库中提取整个表格时,您认为这将会是未来的表现吗?一个简单的'SELECT COUNT()WHERE LessonTitle ='MyNewTitle''就足以知道是否有一个带有该标题的记录,而无需将其全部加载到客户端。 –

+0

@ Karl-JohanSjögren:谢谢你的提问。是的,以这种方式编写是很好的,但我不想再写一个查询来检查重复项,这就是为什么我已经采用了现有的数据源。此外,这仅仅是OP如何实现它的想法。 –

+0

非常感谢你们,我从中学到了很多东西。 – Nian

4

这种独特性应该由数据库执行。为您的表添加唯一约束:

CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title) 
相关问题