Last active
March 25, 2026 22:19
-
-
Save sunmeat/6aa72641346da5a9c34753de1149809b to your computer and use it in GitHub Desktop.
ado net example 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.Data.SqlClient; | |
| using ConsoleTableExt; // !!! dotnet add package ConsoleTableExt (NuGet) | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Console.Title = "Вибірка даних з JOIN"; | |
| Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| string connectionString = "Server=localhost; Database=Store; Integrated Security=True; TrustServerCertificate=True;"; | |
| // SQL-запит з JOIN для вибірки даних з таблиць Product, Category та Producer | |
| string query = @" | |
| SELECT | |
| p.id AS ProductId, | |
| p.name AS ProductName, | |
| p.price, | |
| c.name AS CategoryName, | |
| pr.name AS ProducerName | |
| FROM Product p | |
| INNER JOIN Category c ON p.id_category = c.id | |
| INNER JOIN Producer pr ON p.id_producer = pr.id"; | |
| using (var connection = new SqlConnection(connectionString)) | |
| { | |
| try | |
| { | |
| connection.Open(); | |
| using (var command = new SqlCommand(query, connection)) | |
| { | |
| using (SqlDataReader reader = command.ExecuteReader()) | |
| { | |
| if (reader.HasRows) | |
| { | |
| var data = new List<object[]>(); | |
| // додавання заголовків для таблиці | |
| var headers = new[] { "Product ID", "Назва продукту", "Ціна", "Категорія", "Виробник" }; | |
| data.Add(headers); | |
| while (reader.Read()) | |
| { | |
| var row = new object[] | |
| { | |
| reader.GetInt32(0), // ProductId | |
| reader.GetString(1), // ProductName | |
| reader.GetDouble(2), // Price | |
| reader.GetString(3), // CategoryName | |
| reader.GetString(4) // ProducerName | |
| }; | |
| data.Add(row); | |
| } | |
| ConsoleTableBuilder.From(data) | |
| .WithFormat(ConsoleTableBuilderFormat.Alternative) | |
| .ExportAndWriteLine(); | |
| } | |
| else | |
| { | |
| Console.WriteLine("Немає даних."); | |
| } | |
| } | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| Console.WriteLine("Помилка: " + ex.Message); | |
| } | |
| } | |
| Console.ReadLine(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment