如何在变量中存储从MySQL数据库中获取的单行?

时间:2016-08-25 20:18:09

标签: c# mysql

运行MySqlCommand然后用MySqlDataReader读取一行后,是否可以将整行存储到一个变量中?

MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    // Store a single row into a variable
    // Pass the variable into another method
}

1 个答案:

答案 0 :(得分:1)

关于IDataRecord interface的MSDN文档中解释了您可以实现的最佳功能,但最后您还需要阅读每一列并将其存储在某处。 但是,更面向对象的方法是使用一个类来表示记录中的数据,创建该类的实例并初始化其属性,然后将实例传递给另一个方法

假设您使用的查询是一个简单的

SELECT IDPerson, FirstName, LastName from Persons

现在你已经定义了你的类Person

public class Person
{
    public int IDPerson {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
}

然后你的循环与

一起使用
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    // Declare and initialize the instance of a Person 
    // (this is a single variable as per your requirements)
    Person p = new Person()
    { 
       IDPerson = rdr.GetInt32(0),
       FirstName = rdr.GetString(1),
       LastName  = rdr.GetString(2)
    };
    ProcessPerson(p);
}