Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active March 25, 2026 22:40
Show Gist options
  • Select an option

  • Save sunmeat/5ecc6fdf695d598665f8ccced3f35771 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/5ecc6fdf695d598665f8ccced3f35771 to your computer and use it in GitHub Desktop.
налаштування безпеки в рядку підключення (введення з клавіатури, конфігураційний файл)
using System.Data;
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
// запитуємо у користувача дані для підключення до БД (небезпечно зберігати в коді!)
Console.Write("Введіть ім'я сервера: ");
var serverName = Console.ReadLine();
Console.Write("Введіть ім'я бази даних: ");
var databaseName = Console.ReadLine();
// використовуємо стандартний SqlConnectionStringBuilder для створення рядка підключення
var builder = new SqlConnectionStringBuilder
{
DataSource = serverName,
InitialCatalog = databaseName,
IntegratedSecurity = true, // використовуємо Windows Authentication
TrustServerCertificate = true // потрібно для довіри до сертифіката сервера
};
// отримуємо рядок підключення через builder
string connectionString = builder.ToString();
// альтернативний варіант без builder (закоментовано, бо використовується builder)
// string connectionString = $"Server={serverName}; Database={databaseName}; Integrated Security=True; TrustServerCertificate=True;";
string query = "SELECT id, name, price FROM Product";
var productTable = new DataTable();
using (var connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using (var command = new SqlCommand(query, connection))
{
var dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(productTable);
}
}
catch (Exception ex)
{
Console.WriteLine("Помилка: " + ex.Message);
}
}
// фільтруємо продукти дешевші за 100 грн та сортуємо за id
var filteredRows = productTable.AsEnumerable()
.Where(row => row.Field<double>("price") < 100)
.OrderBy(row => row.Field<int>("id"))
.ToArray();
if (filteredRows.Length > 0)
{
Console.WriteLine("Продукти з ціною менше 100 грн:");
foreach (var row in filteredRows)
{
Console.WriteLine($"{row["id"]}, {row["name"]}, {row["price"]} грн.");
}
}
else
{
Console.WriteLine("Немає продуктів з ціною менше 100 грн.");
}
Console.ReadLine();
}
}
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost; Database=Store; Integrated Security=True; TrustServerCertificate=True;"
}
}
========================================================================================================================
.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>ADO.NET_SQLConnection_Example_1</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ConsoleTableExt" Version="3.3.0" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.1" />
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
</ItemGroup>
</Project>
========================================================================================================================
Program.cs:
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration; // NuGet: Microsoft.Extensions.Configuration, Microsoft.Extensions.Configuration.Json
class Program
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
// завантажуємо конфігурацію з файлу
var configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
// отримуємо рядок підключення з конфігурації
var connectionString = configuration.GetConnectionString("DefaultConnection");
string query = "SELECT id, name, price FROM Product";
var productTable = new DataTable();
using (var connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using (var command = new SqlCommand(query, connection))
{
var dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(productTable);
}
}
catch (Exception ex)
{
Console.WriteLine("Помилка: " + ex.Message);
}
}
// фільтруємо продукти дешевші за 100 грн та сортуємо за id
var filteredRows = productTable.AsEnumerable()
.Where(row => row.Field<double>("price") < 100)
.OrderBy(row => row.Field<int>("id"))
.ToArray();
if (filteredRows.Length > 0)
{
Console.WriteLine("Продукти з ціною менше 100 грн:");
foreach (var row in filteredRows)
{
Console.WriteLine($"{row["id"]}, {row["name"]}, {row["price"]} грн.");
}
}
else
{
Console.WriteLine("Немає продуктів з ціною менше 100 грн.");
}
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment