c# 数据库编程(利用DataSet 和 DataAdaper对象操作数据库--跨表操作)

上篇文章我们介绍了如何利用DataSet 和 DataAdaper对象来对单张表进行操作。

本文我们将介绍如何进行跨表操作。

我们通过具体例子方式进行演示,例子涉及到三张表。

1)student表(学生信息表),有 studentno和studentname两个字段,其中studentno是关键字

2)course表(课程表),有 courseno和coursename两个字段,其中courseno是关键字

3)score表(学生课程考试得分表),有 studentno,couseno,score三个字段,其中studentno,couseno组合为关键字。

例子代码如下:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DbExample
{
    class ActorMoreTable
    {
        public void fetchData()
        {
            DataSet dataSet = new DataSet();
            SqlDataAdapter adapter = null;
            SqlConnection conn = getConnection();
            try
            {
                conn.Open();
                string sql = "select course.courseno as courseno,coursename,student.studentno as studentno, studentname,score " +
                            "from score ,student,course "+
                            "where score.courseno = course.courseno and score.studentno = student.studentno";
                adapter = new SqlDataAdapter(sql, conn);

                adapter.InsertCommand = new SqlCommand(
                    "insert into score(studentno,courseno,score) values(@studentno,@courseno,@score)", conn);
                adapter.InsertCommand.Parameters.Add("@studentno", SqlDbType.Int, 4, "studentno");
                adapter.InsertCommand.Parameters.Add("@courseno", SqlDbType.Int, 4, "courseno");
                adapter.InsertCommand.Parameters.Add("@score", SqlDbType.Int, 4, "score");

                adapter.Fill(dataSet, "score");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "操作失败");
            }
            finally
            {
                conn.Close();
            }
            updateData(dataSet, adapter);
            MessageBox.Show("操作成功");
        }

        private void updateData(DataSet dataSet, SqlDataAdapter adapter)
        {
            DataTable table = dataSet.Tables["score"];
            object[] values = new object[5] { 2, null, 4, null, 65 };
            table.Rows.Add(values);
            adapter.Update(dataSet, "score"); //同步到数据库
        }

        private SqlConnection getConnection()
        {
            string strConnection = @"Data Source = localhost\SQLEXPRESS; Initial Catalog = mydb; User Id = sa; Password = 12345678;";
            SqlConnection conn = new SqlConnection(strConnection);
            return conn;
        }
    }
}

上面代码,我们绑定了一个insert命令。可以看出,关键就是将需要更新的字段与对应的dataset中的字段关联。

 

posted @ 2016-03-28 10:33  51kata  阅读(1389)  评论(0编辑  收藏  举报