Загрузка данных


using Microsoft.Data.Sqlite;

class Program
{
    // Путь к файлу БД (создастся рядом с exe, если его нет)
    private const string DbPath = "drinks.db";
    private static string ConnectionString => $"Data Source={DbPath}";

    static void Main()
    {
        InitializeDatabase(); // создаём таблицы и данные, если БД пустая

        while (true)
        {
            Console.WriteLine("\n=== МЕНЮ ===");
            Console.WriteLine("1) Показать все бренды");
            Console.WriteLine("2) Показать напитки бренда");
            Console.WriteLine("3) Показать все напитки");
            Console.WriteLine("4) Выход");
            Console.Write("Ваш выбор: ");

            var choice = Console.ReadLine();
            Console.WriteLine();

            switch (choice)
            {
                case "1": ShowBrands(); break;
                case "2": ShowDrinksByBrand(); break;
                case "3": ShowAllDrinks(); break;
                case "4": return;
                default: Console.WriteLine("Неверный ввод."); break;
            }
        }
    }

    // ---------- Инициализация БД ----------
    static void InitializeDatabase()
    {
        using var conn = new SqliteConnection(ConnectionString);
        conn.Open();

        var cmd = conn.CreateCommand();
        cmd.CommandText = @"
            CREATE TABLE IF NOT EXISTS brands (
                id   INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT
            );
            CREATE TABLE IF NOT EXISTS drinks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT,
                has_sugar INTEGER,
                alcohol_percentage INTEGER,
                brand_id INTEGER,
                FOREIGN KEY (brand_id) REFERENCES brands(id)
            );";
        cmd.ExecuteNonQuery();

        // Проверяем, есть ли уже данные
        cmd.CommandText = "SELECT COUNT(*) FROM brands;";
        var count = (long)cmd.ExecuteScalar()!;
        if (count > 0) return;

        // Заполняем
        cmd.CommandText = @"
            INSERT INTO brands (name) VALUES ('Coca-Cola'), ('Rich'), ('Жигули');

            INSERT INTO drinks (name, has_sugar, alcohol_percentage, brand_id) VALUES
                ('Coca-Cola Classic', 1, 0, 1),
                ('Coca-Cola Zero',    0, 0, 1),
                ('Sprite',            1, 0, 1),
                ('Rich Апельсин',     1, 0, 2),
                ('Rich Яблоко',       1, 0, 2),
                ('Rich Мультифрукт',  1, 0, 2),
                ('Жигули Барное',     0, 4, 3),
                ('Жигули Классическое', 0, 4, 3),
                ('Жигули Безалкогольное', 1, 0, 3);";
        cmd.ExecuteNonQuery();

        Console.WriteLine("База данных создана и заполнена.");
    }

    // ---------- 1) Все бренды ----------
    static void ShowBrands()
    {
        using var conn = new SqliteConnection(ConnectionString);
        conn.Open();

        var cmd = conn.CreateCommand();
        cmd.CommandText = "SELECT id, name FROM brands;";
        using var reader = cmd.ExecuteReader();

        Console.WriteLine("ID | Бренд");
        Console.WriteLine("----------");
        while (reader.Read())
            Console.WriteLine($"{reader.GetInt32(0),-2} | {reader.GetString(1)}");
    }

    // ---------- 2) Напитки конкретного бренда ----------
    static void ShowDrinksByBrand()
    {
        Console.Write("Введите ID бренда: ");
        if (!int.TryParse(Console.ReadLine(), out int brandId))
        {
            Console.WriteLine("Нужно число.");
            return;
        }

        using var conn = new SqliteConnection(ConnectionString);
        conn.Open();

        var cmd = conn.CreateCommand();
        cmd.CommandText = @"
            SELECT d.name, d.has_sugar, d.alcohol_percentage
            FROM drinks d
            WHERE d.brand_id = $id;";
        cmd.Parameters.AddWithValue("$id", brandId);

        using var reader = cmd.ExecuteReader();
        bool any = false;
        Console.WriteLine("Напиток | Сахар | Алкоголь %");
        Console.WriteLine("-----------------------------");
        while (reader.Read())
        {
            any = true;
            Console.WriteLine(
                $"{reader.GetString(0),-25} | {(reader.GetInt32(1) == 1 ? "да" : "нет"),-5} | {reader.GetInt32(2)}%");
        }

        if (!any) Console.WriteLine("У этого бренда нет напитков (или бренд не найден).");
    }

    // ---------- 3) Все напитки (с JOIN на бренд) ----------
    static void ShowAllDrinks()
    {
        using var conn = new SqliteConnection(ConnectionString);
        conn.Open();

        var cmd = conn.CreateCommand();
        cmd.CommandText = @"
            SELECT d.id, d.name, d.has_sugar, d.alcohol_percentage, b.name
            FROM drinks d
            JOIN brands b ON d.brand_id = b.id
            ORDER BY b.name, d.name;";

        using var reader = cmd.ExecuteReader();
        Console.WriteLine("ID | Напиток                  | Бренд      | Сахар | Алкоголь");
        Console.WriteLine("-------------------------------------------------------------");
        while (reader.Read())
        {
            Console.WriteLine(
                $"{reader.GetInt32(0),-2} | {reader.GetString(1),-24} | {reader.GetString(4),-10} | " +
                $"{(reader.GetInt32(2) == 1 ? "да" : "нет"),-5} | {reader.GetInt32(3)}%");
        }
    }
}