- Course
- SQLite Databases
- Read list from databases
Read list from databases
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that fetches a list of people from an SQLite database. Prepare a Person class with two properties (Name and Age) the first will be of type text and the second of integer type.
To connect to SQLite open a new connection against the database file, then create a new command using the SQLiteCommand
object and finally use the SQLiteDataReader
reader to get all the results in a people list from the following SQL query.
select name, age from person
Remember that to connect to SQLite you will need the reference of System.Data.SQLite
, you can get it from official page or install it directly in your project using the Nuguet package manager, executing the following command in the console:
Install-Package System.Data.SQLite -Version 1.0.112
Input
Output
Juan
26
Sara
35
Solution
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
public class ReadFromSQLite
{
public static string DatabaseFileName = "persons.sqlite";
public static List<Person> Persons = new List<Person>();
public static void Main(string[] args)
{
Read();
foreach (var person in Persons)
{
Console.WriteLine(person.Name);
Console.WriteLine(person.Age);
}
}
public static void Read()
{
using (SQLiteConnection cnx =
new SQLiteConnection("Data Source=" + DatabaseFileName + ";Version=3;"))
{
cnx.Open();
using (SQLiteCommand cmd = cnx.CreateCommand())
{
cmd.CommandText = "select name, age from person";
cmd.CommandType = CommandType.Text;
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Persons.Add(new Person()
{
Name = reader["name"].ToString(),
Age = int.Parse(reader["age"].ToString())
});
}
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}