2013-11-09 108 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) 
相關問題