当前位置:编程学习 > C#/ASP.NET >>

C#数据库插入的两种实现方式


   上图就是以下代码所对应的窗体,包括后面的更新和插入。

         test_dbDataSet.courseRow    cnewrow;      ///     这里的course和faculty是test_dbDataSet下面的两个数据表的名称

            test_dbDataSet.facultyRow   fnewrow;

            if ((courseid.Text == "") || (course.Text == "") || (facultyid.Text == "") || (this.name.Text == "") || (this.num.Text == ""))      /// 这些文本框里放的是待插入的数据


                MessageBox.Show("有一项或者多项没有填写内容,请填写完毕后再提交!");


            else
            {

               /// 第一种方式是在现在数据源在数据编辑器里面对两个表都各自新建一个插入的方法,然后分别调用这两个方法即可实现插入,如下的insertfaculty和insertcourse,后面的参数就是要插入的值。


                if (cb.Text == "tableAdapter.insert")                  
                {
                    int check = facultyTableAdapter.Insertfaculty(this.facultyid.Text, this.name.Text, this.num.Text);
                    int check1 = courseTableAdapter.Insertcourse(this.courseid.Text, this.course.Text, this.facultyid.Text);
                    if ((check > 0) && (check1 > 0))
                    {
                        MessageBox.Show("数据更新成功!");
 
                        facultyid.Text = "";
                        this.insert.Enabled = false;

                    }
                    else
                    {
                        MessageBox.Show("数据更新失败!");
                      
                    }
                    course.Text = "";
                    courseid.Text = "";
                    this.name.Text = "";
                    this.num.Text = "";

                    courseid.Focus();
                }

 

          /// 第二种方法是对两个表都新建一个该表的新行,然后在新行中插入数据,再将该新行加到相应的数据表,最后更新数据库。
                else
                {
                    fnewrow = test_dbDataSet.faculty.NewfacultyRow();


                    fnewrow.faculty_id = this.facultyid.Text;


                    fnewrow.name = this.name.Text;


                    fnewrow.num = this.num.Text;


                    test_dbDataSet.faculty.Rows.Add(fnewrow);


                    int i = facultyTableAdapter.Update(test_dbDataSet.faculty);    ///更新数据库

 


                   
                    cnewrow = test_dbDataSet.course.NewcourseRow();


                    cnewrow.course_id = courseid.Text;


                    cnewrow.course = this.course.Text;


                    cnewrow.faculty_id = this.facultyid.Text;


                    test_dbDataSet.course.Rows.Add(cnewrow);


                    int t = courseTableAdapter.Update(test_dbDataSet.course);


                    if ((t > 0) && (i > 0))
                    {
                        MessageBox.Show("第二种方法成功插入数据!");
                        this.facultyid.Text = "&

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,