c# - 从sql中解析对象

标签 c# sql sqlite

我已经创建了表格并将几行放入其中。有没有办法从表中解析我自己的对象?

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/

相关文章:

c# - 在 C# 中动态评估字符串条件

c# - TcpClient 未连接

c# - Json.NET 是否缓存类型的序列化信息?

c# - 如何为实际使用我的数据库上下文的 ASP.NET Core Controller 编写单元测试?

python - sqlite3 -- 无法打开数据库文件

php - 使用单个查询更新时自动增量 MySQL 列字段

java - 如何检查Android中是否存在数据库?

php - 如何从特定行开始计算表格的所有行

.net - 使用 ODBC 和 C++ Net 将空 BLOB 插入 SQLite DB

python - 为什么我突然得到 "OperationalError: no such table"?