|
|
@@ -0,0 +1,390 @@
|
|
|
+using System.Text;
|
|
|
+using Npgsql;
|
|
|
+
|
|
|
+class TrainingDatabase
|
|
|
+{
|
|
|
+ private NpgsqlConnection conn;
|
|
|
+
|
|
|
+ private bool IsValidPhone(string phone)
|
|
|
+ {
|
|
|
+ if (phone.Length != 11) return false;
|
|
|
+ foreach (char c in phone)
|
|
|
+ {
|
|
|
+ if (!char.IsDigit(c)) return false;
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private void ExecuteQuery(string query, NpgsqlParameter[] parameters = null)
|
|
|
+ {
|
|
|
+ using (var cmd = new NpgsqlCommand(query, conn))
|
|
|
+ {
|
|
|
+ if (parameters != null)
|
|
|
+ cmd.Parameters.AddRange(parameters);
|
|
|
+
|
|
|
+ try
|
|
|
+ {
|
|
|
+ cmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ Console.WriteLine("Ошибка: " + ex.Message);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private bool IsConnected()
|
|
|
+ {
|
|
|
+ return conn.State == System.Data.ConnectionState.Open;
|
|
|
+ }
|
|
|
+
|
|
|
+ public TrainingDatabase()
|
|
|
+ {
|
|
|
+ string connectionString = "Host=edu-pg.itiscaf.ru;Port=5432;Database=dbwork;Username=andreev_as;Password=S5#&H680$KE";
|
|
|
+ conn = new NpgsqlConnection(connectionString);
|
|
|
+
|
|
|
+ try
|
|
|
+ {
|
|
|
+ conn.Open();
|
|
|
+ Console.WriteLine("Подключение успешно");
|
|
|
+ }
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ Console.WriteLine("Не удалось подключиться к базе данных: " + ex.Message);
|
|
|
+ Environment.Exit(1);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ ~TrainingDatabase()
|
|
|
+ {
|
|
|
+ if (conn != null)
|
|
|
+ conn.Close();
|
|
|
+ }
|
|
|
+
|
|
|
+ private string ConvertToUtf8(string text)
|
|
|
+ {
|
|
|
+ if (string.IsNullOrEmpty(text)) return text;
|
|
|
+ byte[] win1251Bytes = Encoding.GetEncoding(1251).GetBytes(text);
|
|
|
+ return Encoding.UTF8.GetString(win1251Bytes);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void AddUser()
|
|
|
+ {
|
|
|
+ string name, secondName, lastName, phone;
|
|
|
+ int membershipId;
|
|
|
+
|
|
|
+ Console.Write("Имя: ");
|
|
|
+ name = Console.ReadLine();
|
|
|
+ Console.Write("Фамилия: ");
|
|
|
+ secondName = Console.ReadLine();
|
|
|
+ Console.Write("Отчество: ");
|
|
|
+ lastName = Console.ReadLine();
|
|
|
+ Console.Write("Телефон (11 цифр): ");
|
|
|
+ phone = Console.ReadLine();
|
|
|
+
|
|
|
+ if (!IsValidPhone(phone))
|
|
|
+ {
|
|
|
+ Console.WriteLine("Ошибка: телефон должен содержать 11 цифр");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ Console.Write("id абонемента: ");
|
|
|
+ membershipId = int.Parse(Console.ReadLine());
|
|
|
+
|
|
|
+ string getMembershipQuery = "select total_sessions, validity_days from membership where id = @id";
|
|
|
+
|
|
|
+ using (var cmd = new NpgsqlCommand(getMembershipQuery, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@id", membershipId);
|
|
|
+ using (var reader = cmd.ExecuteReader())
|
|
|
+ {
|
|
|
+ if (reader.Read())
|
|
|
+ {
|
|
|
+ int totalSessions = reader.GetInt32(0);
|
|
|
+ int validityDays = reader.GetInt32(1);
|
|
|
+ DateTime validUntil = DateTime.Now.AddDays(validityDays);
|
|
|
+
|
|
|
+ reader.Close();
|
|
|
+
|
|
|
+ string insertQuery = "insert into users_gym (users_name, users_second_name, users_last_name, phone, membership_id, remaining_sessions, valid_until) values (@name, @secondName, @lastName, @phone, @membershipId, @remaining, @validUntil)";
|
|
|
+
|
|
|
+ using (var insertCmd = new NpgsqlCommand(insertQuery, conn))
|
|
|
+ {
|
|
|
+ insertCmd.Parameters.AddWithValue("@name", name);
|
|
|
+ insertCmd.Parameters.AddWithValue("@secondName", secondName);
|
|
|
+ insertCmd.Parameters.AddWithValue("@lastName", lastName);
|
|
|
+ insertCmd.Parameters.AddWithValue("@phone", phone);
|
|
|
+ insertCmd.Parameters.AddWithValue("@membershipId", membershipId);
|
|
|
+ insertCmd.Parameters.AddWithValue("@remaining", totalSessions);
|
|
|
+ insertCmd.Parameters.AddWithValue("@validUntil", validUntil);
|
|
|
+
|
|
|
+ int rows = insertCmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+
|
|
|
+ Console.WriteLine("Пользователь добавлен");
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ Console.WriteLine("Абонемент с таким id не найден");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void AddTraining()
|
|
|
+ {
|
|
|
+ string sessionDate;
|
|
|
+ int userId, coachId, hallId;
|
|
|
+
|
|
|
+ Console.Write("id пользователя: ");
|
|
|
+ userId = int.Parse(Console.ReadLine());
|
|
|
+ Console.Write("id тренера: ");
|
|
|
+ coachId = int.Parse(Console.ReadLine());
|
|
|
+ Console.Write("id зала: ");
|
|
|
+ hallId = int.Parse(Console.ReadLine());
|
|
|
+ Console.Write("Дата тренировки (гггг-мм-дд): ");
|
|
|
+ sessionDate = Console.ReadLine();
|
|
|
+
|
|
|
+ DateTime date;
|
|
|
+ if (!DateTime.TryParse(sessionDate, out date))
|
|
|
+ {
|
|
|
+ Console.WriteLine("Неверный формат даты");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ string query = "insert into training_session (session_date, user_id, coach_id, hall_id) values (@date, @userId, @coachId, @hallId)";
|
|
|
+
|
|
|
+ using (var cmd = new NpgsqlCommand(query, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@date", date);
|
|
|
+ cmd.Parameters.AddWithValue("@userId", userId);
|
|
|
+ cmd.Parameters.AddWithValue("@coachId", coachId);
|
|
|
+ cmd.Parameters.AddWithValue("@hallId", hallId);
|
|
|
+ cmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+
|
|
|
+ Console.WriteLine("Тренировка добавлена");
|
|
|
+ }
|
|
|
+
|
|
|
+ public void EditUser()
|
|
|
+ {
|
|
|
+ int userId;
|
|
|
+ string phone;
|
|
|
+ int remainingSessions;
|
|
|
+ string validUntil;
|
|
|
+
|
|
|
+ Console.Write("id пользователя для редактирования: ");
|
|
|
+ userId = int.Parse(Console.ReadLine());
|
|
|
+ Console.Write("Новый телефон: ");
|
|
|
+ phone = Console.ReadLine();
|
|
|
+
|
|
|
+ if (!IsValidPhone(phone))
|
|
|
+ {
|
|
|
+ Console.WriteLine("Ошибка: телефон должен содержать 11 цифр");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ Console.Write("Новый остаток тренировок: ");
|
|
|
+ remainingSessions = int.Parse(Console.ReadLine());
|
|
|
+ Console.Write("Новая дата окончания (гггг-мм-дд): ");
|
|
|
+ validUntil = Console.ReadLine();
|
|
|
+
|
|
|
+ DateTime date;
|
|
|
+ if (!DateTime.TryParse(validUntil, out date))
|
|
|
+ {
|
|
|
+ Console.WriteLine("Неверный формат даты");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ string query = "update users_gym set phone = @phone, remaining_sessions = @remaining, valid_until = @validUntil where id = @id";
|
|
|
+
|
|
|
+ using (var cmd = new NpgsqlCommand(query, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@phone", phone);
|
|
|
+ cmd.Parameters.AddWithValue("@remaining", remainingSessions);
|
|
|
+ cmd.Parameters.AddWithValue("@validUntil", date);
|
|
|
+ cmd.Parameters.AddWithValue("@id", userId);
|
|
|
+ cmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+
|
|
|
+ Console.WriteLine("Данные пользователя обновлены");
|
|
|
+ }
|
|
|
+
|
|
|
+ public void DeleteUser()
|
|
|
+ {
|
|
|
+ int userId;
|
|
|
+ Console.Write("id пользователя для удаления: ");
|
|
|
+ userId = int.Parse(Console.ReadLine());
|
|
|
+
|
|
|
+ string query1 = "delete from training_session where user_id = @id";
|
|
|
+ using (var cmd = new NpgsqlCommand(query1, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@id", userId);
|
|
|
+ cmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+
|
|
|
+ string query2 = "delete from users_gym where id = @id";
|
|
|
+ using (var cmd = new NpgsqlCommand(query2, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@id", userId);
|
|
|
+ cmd.ExecuteNonQuery();
|
|
|
+ }
|
|
|
+
|
|
|
+ Console.WriteLine("Пользователь удален");
|
|
|
+ }
|
|
|
+
|
|
|
+ public void SearchUsers()
|
|
|
+ {
|
|
|
+ string searchTerm;
|
|
|
+ Console.Write("Введите фамилию для поиска: ");
|
|
|
+ searchTerm = Console.ReadLine();
|
|
|
+
|
|
|
+ string query = "select id, convert_from(users_name::bytea, 'UTF8') as users_name, convert_from(users_second_name::bytea, 'UTF8') as users_second_name, convert_from(users_last_name::bytea, 'UTF8') as users_last_name, phone, remaining_sessions, valid_until from users_gym where users_second_name ilike @search order by users_second_name";
|
|
|
+
|
|
|
+ using (var cmd = new NpgsqlCommand(query, conn))
|
|
|
+ {
|
|
|
+ cmd.Parameters.AddWithValue("@search", "%" + searchTerm + "%");
|
|
|
+ using (var reader = cmd.ExecuteReader())
|
|
|
+ {
|
|
|
+ if (!reader.HasRows)
|
|
|
+ {
|
|
|
+ Console.WriteLine("Ничего не найдено");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ var results = new List<string[]>();
|
|
|
+ while (reader.Read())
|
|
|
+ {
|
|
|
+ var row = new string[reader.FieldCount];
|
|
|
+ Console.WriteLine($"\nid: {reader["id"]}");
|
|
|
+ Console.WriteLine($"Имя: {reader["users_name"]}");
|
|
|
+ Console.WriteLine($"Фамилия: {reader["users_second_name"]}");
|
|
|
+ Console.WriteLine($"Отчество: {reader["users_last_name"]}");
|
|
|
+ Console.WriteLine($"Телефон: {reader["phone"]}");
|
|
|
+ Console.WriteLine($"Остаток тренировок: {reader["remaining_sessions"]}");
|
|
|
+ Console.WriteLine($"Абонемент действует до: {reader["valid_until"]} \n");
|
|
|
+
|
|
|
+ for (int i = 0; i < reader.FieldCount; i++)
|
|
|
+ {
|
|
|
+ row[i] = reader.GetValue(i).ToString();
|
|
|
+ }
|
|
|
+ results.Add(row);
|
|
|
+ }
|
|
|
+ Console.WriteLine($"Найдено {results.Count} записей");
|
|
|
+ ExportToCsv(results);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void ShowAllUsers()
|
|
|
+ {
|
|
|
+ string query = "select id, users_name, users_second_name, users_last_name, phone, remaining_sessions, valid_until from users_gym order by id";
|
|
|
+
|
|
|
+ using (var cmd = new NpgsqlCommand(query, conn))
|
|
|
+ using (var reader = cmd.ExecuteReader())
|
|
|
+ {
|
|
|
+ if (!reader.HasRows)
|
|
|
+ {
|
|
|
+ Console.WriteLine("Нет данных в таблице");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ while (reader.Read())
|
|
|
+ {
|
|
|
+ Console.WriteLine($"\nid: {reader["id"]}");
|
|
|
+ Console.WriteLine($"Имя: {reader["users_name"]}");
|
|
|
+ Console.WriteLine($"Фамилия: {reader["users_second_name"]}");
|
|
|
+ Console.WriteLine($"Отчество: {reader["users_last_name"]}");
|
|
|
+ Console.WriteLine($"Телефон: {reader["phone"]}");
|
|
|
+ Console.WriteLine($"Остаток тренировок: {reader["remaining_sessions"]}");
|
|
|
+ Console.WriteLine($"Абонемент действует до: {reader["valid_until"]}\n");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void ExportToCsv(List<string[]> data)
|
|
|
+ {
|
|
|
+ string filename = "export_" + DateTime.Now.Ticks + ".csv";
|
|
|
+
|
|
|
+ using (var file = new StreamWriter(filename, false, Encoding.UTF8))
|
|
|
+ {
|
|
|
+ if (data.Count > 0)
|
|
|
+ {
|
|
|
+ for (int i = 0; i < data[0].Length; i++)
|
|
|
+ {
|
|
|
+ file.Write($"Column{i + 1}");
|
|
|
+ if (i < data[0].Length - 1) file.Write(",");
|
|
|
+ }
|
|
|
+ file.WriteLine();
|
|
|
+
|
|
|
+ foreach (var row in data)
|
|
|
+ {
|
|
|
+ for (int i = 0; i < row.Length; i++)
|
|
|
+ {
|
|
|
+ file.Write(row[i]);
|
|
|
+ if (i < row.Length - 1) file.Write(",");
|
|
|
+ }
|
|
|
+ file.WriteLine();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Console.WriteLine("Файл сохранён в: " + Directory.GetCurrentDirectory());
|
|
|
+ }
|
|
|
+
|
|
|
+ public void ShowMenu()
|
|
|
+ {
|
|
|
+ int choice;
|
|
|
+ while (true)
|
|
|
+ {
|
|
|
+ Console.WriteLine();
|
|
|
+ Console.WriteLine("1. Показать всех пользователей");
|
|
|
+ Console.WriteLine("2. Добавить пользователя");
|
|
|
+ Console.WriteLine("3. Добавить тренировку");
|
|
|
+ Console.WriteLine("4. Редактировать пользователя");
|
|
|
+ Console.WriteLine("5. Удалить пользователя");
|
|
|
+ Console.WriteLine("6. Поиск пользователей");
|
|
|
+ Console.WriteLine("0. Выход");
|
|
|
+ Console.Write("Выбор: ");
|
|
|
+
|
|
|
+ if (!int.TryParse(Console.ReadLine(), out choice))
|
|
|
+ {
|
|
|
+ Console.WriteLine("Неверный выбор");
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ switch (choice)
|
|
|
+ {
|
|
|
+ case 1:
|
|
|
+ ShowAllUsers();
|
|
|
+ break;
|
|
|
+ case 2:
|
|
|
+ AddUser();
|
|
|
+ break;
|
|
|
+ case 3:
|
|
|
+ AddTraining();
|
|
|
+ break;
|
|
|
+ case 4:
|
|
|
+ EditUser();
|
|
|
+ break;
|
|
|
+ case 5:
|
|
|
+ DeleteUser();
|
|
|
+ break;
|
|
|
+ case 6:
|
|
|
+ SearchUsers();
|
|
|
+ break;
|
|
|
+ case 0:
|
|
|
+ return;
|
|
|
+ default:
|
|
|
+ Console.WriteLine("Неверный выбор");
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ Console.OutputEncoding = Encoding.UTF8;
|
|
|
+ Console.WriteLine("Учёт тренировок спортсменов");
|
|
|
+ TrainingDatabase db = new TrainingDatabase();
|
|
|
+ db.ShowMenu();
|
|
|
+ }
|
|
|
+}
|