避免将重复数据插入db:asp.net

时间:2018-10-24 09:26:42

标签: c# asp.net sql-server

我想将一门课程插入到具有StudentId和CourseId字段的数据库表中。 而且我不想为每个学生插入重复的课程。 我为此使用以下代码。但是,如果我在运行程序后为每位学生仅插入一门课程,则会显示“该单元已经在数据库中注册”

 //Avooid Insert Duplicate StudentId data to db
            DataSet ds = new DataSet();
            SqlCommand CmdDuplicate = new SqlCommand("select * from EDU_Student_Course_Registration where StudentId Like N'%" + LblStudentId.Text + "%'", con);
            SqlDataAdapter da = new SqlDataAdapter(CmdDuplicate);
            da.Fill(ds);
            int j = ds.Tables[0].Rows.Count;
            //int s=ds
            //Avooid Insert Duplicate CourseId data to db
            DataSet ds2 = new DataSet();
            SqlCommand CmdDuplicate2 = new SqlCommand("select * from EDU_Student_Course_Registration where CourseId Like N'%" + LblCourseId.Text + "%'", con);
            SqlDataAdapter da2 = new SqlDataAdapter(CmdDuplicate2);
            da2.Fill(ds2);
            int j2 = ds.Tables[0].Rows.Count;
            if (j > 0 && j2 > 0)
            {
                string myStringVariable1 = "This unit has already been registered in the database";
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable1 + "');", true);
                ds.Clear();
                ds2.Clear();
            }
            else
            {
                //// insert the data of [EDU_Student_Course_Registration] Table
                string Sqlstr_SSLesson = " Insert Into EDU_Student_Course_Registration (" + " StudentId," + " CourseId," + " CreateDate " + " ) " +
              "VALUES ('" + Int32.Parse(LblStudentId.Text) + "' ,'" + Int32.Parse(LblCourseId.Text) + "','" + obj.CreateDateTime() + "')";
                sqlcom.CommandText = Sqlstr_SSLesson;
                con.Open();
                sqlcom.Connection = con;
                sqlcom.ExecuteNonQuery();
                sqlcom.Connection.Close();
                string myStringVariable = "Your information has been successfully recorded";
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);
            }

我想怎么做?!

1 个答案:

答案 0 :(得分:0)

您当前的测试:此课程是否存在该表中带有此StudentId的任何行,无论课程+该课程ID是否存在于该表中的任何行中,无论学生是什么。

将其更改为单个测试:此学生ID和课程ID在此表中是否存在任何行。