DY

13 .Net Core & SQLite

Nous allons découvrir dans ce TP comment lier notre programme .Net Core avec une base de données. Pour ce faire nous utiliserons le SGBD SQLite.

Mise en place du projet console

Il convient de créer un projet comme d'habitude

mdkir sqlite_csharp_demo
cd sqlite_csharp_demo
dotnet new console

Puis on ajoute le package SQLite pour C#

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet restore

Connexion à une BDD

Il convient d'importer l'espace de nom correspondant au package SQLite

using Microsoft.Data.Sqlite;

Il convient dans un un premier temps de créer une connexion à la bdd

static SqliteConnection connect(String datasource)
{
    SqliteConnectionStringBuilder connectionBuilder = new SqliteConnectionStringBuilder();
    connectionBuilder.DataSource = datasource;
    return new SqliteConnection(connectionBuilder.ConnectionString);
}

 static void Main(string[] args)
{
    SqliteConnection connection = null;

    connection = connect("data.sqlite3");

    connection.Open();
}

Si vous lancez votre programme via un dotnet run, une base de données sqlite3 vide sera créé. Il est donc temps de créer une table dans cette base de données:

static void createBeerTable(SqliteConnection connection)
{
    SqliteCommand command = connection.CreateCommand();
    command.CommandText = "CREATE TABLE IF NOT EXISTS beers(id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, name TEXT);";
    command.ExecuteNonQuery();
}

Et si on insérait un enregistrement ?

static void createBeer(String beer, SqliteConnection connection)
{
    SqliteCommand command = connection.CreateCommand();
    command.CommandText = "INSERT INTO beers (name) VALUES (@name)";
    command.Parameters.Add(new SqliteParameter("@name", beer));
    command.ExecuteNonQuery();
}

Et enfin pour lire toutes les données issues de la table:

static Dictionary<int, string> getAllBeers(SqliteConnection connection)
{
    Dictionary<int, string> beers = new Dictionary<int, string>();

    SqliteCommand command = connection.CreateCommand();
    command.CommandText = "SELECT id, name FROM beers";
    using (SqliteDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            beers.Add(reader.GetInt32(0), reader.GetString(1));
        }
    }
    return beers;
}

Pour parcourir un Dictionnaire on peut utiliser le code suivant:

foreach(KeyValuePair<int, string> row in getAllBeers(connection))
{
    Console.WriteLine("id: {0} name: {1}", row.Key, row.Value);
}

A vous de jouer