當用戶輸入重複的數據時,我該如何防止在數據庫中複製「課程標題」?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");
通過第一選擇,並檢查是否字符串已經存在,如果沒有,插入,如果它存在,什麼也不做。 – Max
您也可以通過直接在數據庫中對錶列使用唯一約束來防止重複。以下是它的方式:http://technet.microsoft.com/en-us/library/ms190024.aspx –
你能提供一些例子嗎?我是新來的,謝謝。 – Nian