我有一个名为ViewComments()的函数,它使用SQL命令从数据库中检索内容
private void ViewComments()
{
hookUp = new SqlConnection("Server=XXXX\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand("SELECT PersonName,PersonMail,Comment FROM CommentsTable", hookUp);
try
{
hookUp.Open();
reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
SQL_Result.Text += reader["PersonName"] + " " + reader["PersonMail"] + " " + reader["Comment"] + Convert.ToString(reader["PostDate"]) + "<br/>";
}
}
catch (Exception)
{
MessageBox.Show("Error in database code\n");
}
finally
{
reader.Close();
hookUp.Close();
}
}
我想将内容存储在IList<>
控件中,该怎么做?
谢谢你..
答案 0 :(得分:3)
创建一个具有所需值属性的类:
public class Comment
{
public string PersonName {get;set;}
public string PersonMail {get;set;}
public string Comment {get;set;}
public string PostDate {get;set;}
}
然后创建一个列表并用值填充:
List<Comment> comments = new List<Comment>();
...
while (reader.Read())
{
comments.Add(new Comment()
{
PersonName = reader["PersonName"],
PersonMail = reader["PersonMail"],
Comment = reader["Comment"],
PostDate = Convert.ToString(reader["PostDate"])
});
}
答案 1 :(得分:1)
您还可以使用LINQ to SQL为您创建类。你这样做:
然后,要在代码中查询数据库,您可以执行以下操作:
private void QueryMyData()
{
MyDbmlFileNameDataContext context = new MyDbmlFileNameDataContext("Server=XXXX\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
var query = from c in context.CommentsTable
where c.PersonName == "John Doe" // This is optional if you want to sub-select.
select c;
foreach (var comment in query)
{
Console.WriteLine(comment.PersonName + " " + comment.PersonMail + " " comment.Comment);
}
}
警告:根据我个人的经验,LINQ对于极大的数据集似乎不是很有效。