从C#中的多个表中读取-如何? [英] Reading from multiple tables in C# - how?
问题描述
嗨.
我想这是一个非常简单的问题,但我确实找不到适合我需求的答案!
我在MySQL数据库中有2个表:
家庭
-FamilyId
-城市
-电话
成员
-FamilyId
-Birtdate
家庭ID当然是将成员绑定到家庭的主键.
所以我想要的是获取正确的家庭行,以及属于该家庭的所有成员行,如下所示:
Hi.
I guess this is a very simple question, but I really can''t find the answer that suits my needs!
What I have is 2 tables in a MySQL database:
Families
- FamilyId
- City
- Phone
Members
- FamilyId
- Birtdate
The family id is of course the primary key, that binds members to a family.
So what I want is to get the right family row, and all member rows that belongs to this family like this:
string Query="SELECT * FROM `Families`, `Members` WHERE `Families`.`FamilyId`=''123'' AND `Members`.`FamilyId`=''123'';";
但是,如何遍历结果,以便可以创建相应的系列对象以及C#应用程序中具有的相应Member对象?
But how do I iterate over the result, so that I can create the corresponding family object, and the corresponding Member objects that I have in my C# application?
MysqlConnection.Open();
MySqlCommand MysqlCommand=new MySqlCommand(Query,MysqlConnection);
MysqlReader=MysqlCommand.ExecuteReader();
while (MysqlReader.Read()) {
//what should I do here?
}
非常感谢!
Thanks a lot!
推荐答案
在执行查询
"SELECT * FROM `Families`, `Members` WHERE `Families`.`FamilyId`='123' AND `Members`.`FamilyId`='123'"
将家庭和成员"表加入1个结果集中.
输出结果将是
You join the to tables Families and Members into 1 result set.
The output result will be
FamilyId,City,Phone,FamilyId,Birtdate
最后返回的每一行有5列.
在您的while循环中,您可以执行以下操作:
Ending up with 5 column on each row returned.
In your while loop you can then do:
while (reader.Read())
{
FamiliesObject f = new FamiliesObject((int)reader[0], (string)reader[1], (string)reader[2]); // Column FamilyId, City, Phone
MembersObject m = new MembersObject((int)reader[3], (DateTime)reader[4]); // Column FamilyId and Birtdate
}
您必须创建FamiliesObject和MembersObject类.而且FamiliesObject可能看起来像这样.
You have to create FamiliesObject and MembersObject class. And FamiliesObject could look like this.
public class FamiliesObject
{
public int FamilyId;
public string City;
public string Phone;
public FamiliesObject(int familyId, string city, string phone)
{
this.FamilyId = familyId;
this.City = city;
this.Phone = phone;
}
}
希望您能理解:-)
Hope you get the idea :-)
在遍历过程中,读取5个值,并调用两个构造函数,每个构造函数分别取3个值,并将它们放在列表中,也许检查一下首先,他们还不存在.
Well, as you iterate through, read the 5 values, and call the two constructors taking 3 values each, and put them in a list, perhaps checking first that they are not there already.
这篇关于从C#中的多个表中读取-如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!