当用户输入重复的数据时,我该如何防止在数据库中复制“课程标题”?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