我已经创建了表格并将几行放入其中。有没有办法从表中解析我自己的对象?
class Human
{
string name;
int age;
public Human(string name, int age)
{
this.name = name;
this.age = age;
}
}
-- create table
string sql = "create table human (name varchar(20), age int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
-- insert sample data
string sql = "insert into human (name, age) values ('John', 20)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
-- get the data back from that table
string sql = "select * from human";
command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
现在如何从我的阅读器中解析一个Human
实例?
最佳答案
是的,你可以
其实很简单。 试试这个:
//Create Collection of Human to store the values
List<Human> Humans = new List<Human>();
while (reader.Read())
{
//Create Human Object from Sql Reader
Human h=new Human(reader.getString(0),reader.getInt(1));
//Add the object to collection
Humans.add(h);
}
Humans 会将您获得的所有 Human Object 排成一行。
关于c# - 从sql中解析对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691471/