简体   繁体   English

如何在C#中添加第二个表并从数据集中的两个表中获取数据

[英]how to add second table and get data from both tables in dataset in c#

I m fetching data from database through c# to my asp.net file in dataset.. my c# code is like this: 我正在通过c#从数据库中获取数据到数据集中的asp.net文件中。我的c#代码是这样的:

{
Datalist a = e.Item.FindControl("abc") as DataList;
a.DataSource = GetData("select * from xyz where ID='" +((System.Data.DataRowView)(e.Item.DataItem)).Row[0] + "' AND LIMIT 1");

a.DataBind();
}

Its working fine.. but i want to add another table to it.. means i want to data from two table of database.. 它的工作正常..但我想向其中添加另一个表..这意味着我想从数据库的两个表中获取数据。

I know how to do it with ExecuteReader() and Mysql Command.. but i dont know anythiong about this DataSource.. I am new to asp and c# so pls .. any help.. thank you so much 我知道如何使用ExecuteReader()和Mysql Command ..但我不知道有关此DataSource的问题。.我是ASP和C#的新手,所以..有什么帮助..非常感谢

here that function GetData() 这里的功能GetData()

private DataTable GetData(string query)
    {
        DataTable dt = new DataTable();
        string constr = ConfigurationManager.ConnectionStrings["SpeedyFlower"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand(query))
            {
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }

Check if this works for you: 检查是否适合您:

SqlDataAdapter adapter = new SqlDataAdapter(
      "SELECT * FROM employee1; SELECT * FROM employee2", connection);
adapter.TableMappings.Add("Table", "employee1");
adapter.TableMappings.Add("Table1", "employee2");
adapter.Fill(ds);

Now you have 2 tables in dataset ds as: 现在,数据集ds中有2个表,如下所示:

ds.Tables[0] //table employee1
ds.Tables[1] //table employee2

Put this code under GetData function (where you are makeing call to MySQLDataAdapter). 将此代码放在GetData函数下(您将在其中调用MySQLDataAdapter)。 In query just pass both the query for both the tables. 在查询中只需传递两个表的查询即可。 Please note that TableMapping is optional and is not madatory. 请注意,TableMapping是可选的,不是必须的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM