1

I've created the table and put several rows into it. Is there a way to parse my own objects from table?

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())

Now how do I parse a Human instance from my reader?

2
  • Also: in your last query, do not call .ExecuteQuery() after you've already called .EXecuteReader! Just one call, please - and since you want to get back the result set, you need .ExecuteReader() .... Commented Jan 9, 2016 at 9:34
  • @marc_s It's a sample for the question, it's not a real code, but anyway - thank you! Commented Jan 9, 2016 at 10:25

2 Answers 2

2

Yes you can

Its very simple infact. Try this:

//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 Will have all the Human Object you get as rows.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, there is a way. I would suggest using Entity Framework which essentially allows you to bind types in your code to tables in the database.

For SQLite, here are a couple of links to get you started:

http://www.bricelam.net/2012/10/entity-framework-on-sqlite.html

http://erikej.blogspot.co.uk/2014/11/using-sqlite-with-entity-framework-6.html

3 Comments

This might make a more useful comment--the asker was really wondering about how to get data out of that data reader, which they've set up. EF is sometimes a better option, for some situations, and it's probably worth bringing up, but it's not really an answer to the question that was asked.
My project is little not really complex, with no resterictions on time or speed, so I don't really need to complicate it more with framework. Still thank you for the help!
Thanks @MatthewHaugen for the advice - in hindsight, I agree. XSIon, you're welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.