我对编程很新,我正试图绕着课程。我创建了一个类如下的类:
public class HistoricalEvents
{
public DateTime historicDate { get; set; }
public string historicEvent { get; set; }
}
我希望能够进入MySQL数据库,拉出多个事件,然后将这些事件显示在屏幕上。如何从MySQL创建多个HistoricalEvent,然后迭代它们以将它们显示在屏幕上?
答案 0 :(得分:3)
首先,您需要一个代表单个事件的类,最好以单数形式命名(例如HistoricalEvent
而不是HistoricalEvents
)。
然后您可以像这样创建List<HistoricalEvent>
:
public class HistoricalEvent
{
public DateTime historicDate { get; set; }
public decimal historicEvent { get; set; }
}
List<HistoricalEvent> historicalEvents = new List<HistoricalEvent>();
historicalEvents.Add(new HistoricalEvent());
// ... etc etc ...
获得列表后,可以像这样迭代:
foreach (HistoricalEvent historicalEvent in historicalEvents)
{
// "historicalEvent" contains the current HistoricalEvent :)
}
从MySQL数据库创建对象涉及更多。如果你想进入,试试this tutorial(由微软提供),也许可以查看linq to objects,但我建议先熟悉C#:)
这听起来有点简洁,所以这是一个类似的例子:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>();
people.Add(new Person()
{
Name = "Dave",
Age = 43
});
people.Add(new Person()
{
Name = "Wendy",
Age = 39
});
foreach (Person person in People)
{
Console.WriteLine(person.Name) // "Dave", then "Wendy"
}
答案 1 :(得分:1)
这使用Connector/Net ADO.Net提供商:
var list = new List<HistoricalEvent>();
using (var cn = new MySqlConnection())
{
cn.Open();
var sql = "SELECT Date, Event FROM HistoricalEvents";
using(var cm = new MySqlCommand(sql, cn))
using(var dr = cm.ExecuteReader())
{
while (dr.Read)
list.Add(new HistoricalEvent
{
historicDate = dr.GetDate(0),
historicEvent= dr.GetString(1)
});
}
}
foreach (var item in list)
Console.WriteLine("{0}: {1}",item.historicDate,item.historicEvent);