首页 > 其他 > 详细

DataSet 多表关系

时间:2014-07-28 02:55:10      阅读:407      评论:0      收藏:0      [点我收藏+]

bubuko.com,布布扣

        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString = @"Data Source=.;Initial Catalog=Pubs;Integrated Security=SSPI";
            string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";

            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet dsPubs = new DataSet();

            try
            {
                con.Open();
                adapter.Fill(dsPubs, "Authors");

                cmd.CommandText = "SELECT au_id, title_id FROM TitleAuthor";
                adapter.Fill(dsPubs, "TitleAuthor");

                cmd.CommandText = "SELECT title_id, title FROM Titles";
                adapter.Fill(dsPubs, "Titles");

                //多对多关系
                DataRelation Titles_TitleAuthor = new DataRelation("Titles_TitleAuthor",
                    dsPubs.Tables["Titles"].Columns["title_id"],
                    dsPubs.Tables["TitleAuthor"].Columns["title_id"]);

                DataRelation Authors_TitleAuthor = new DataRelation("Authors_TitleAuthor",
                    dsPubs.Tables["Authors"].Columns["au_id"],
                    dsPubs.Tables["TitleAuthor"].Columns["au_id"]);

                dsPubs.Relations.Add(Titles_TitleAuthor);
                dsPubs.Relations.Add(Authors_TitleAuthor);

                foreach (DataRow rowAuthor in dsPubs.Tables["Authors"].Rows)
                {
                    lblList.Text += "<br /><b>" + rowAuthor["au_fname"];
                    lblList.Text += " " + rowAuthor["au_lname"] + "</b><br />";
                    foreach (DataRow rowTitleAuthor in rowAuthor.GetChildRows(Authors_TitleAuthor))
                    {
                        DataRow rowTitle = rowTitleAuthor.GetParentRows(Titles_TitleAuthor)[0];
                        lblList.Text += "  ";
                        lblList.Text += rowTitle["title"] + "<br />";
                    }
                }

            }
            catch (Exception err)
            {
                lblList.Text = "Error reading list of names. ";
                lblList.Text = err.Message;
            }
            finally
            {
                con.Close();
            }
        }

 

DataSet 多表关系,布布扣,bubuko.com

DataSet 多表关系

原文:http://www.cnblogs.com/wanghaibin/p/3872087.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!