//Додаємо новий контакт в БД public int InsertContact(Contact contact) { try { comm.CommandText = "INSERT INTO Contacts(UserId,FirstN,LastN,MiddleN,PhoneNum,Adress) VALUES(@UserId,@FirstN,@LastN,@MiddleN,@PhoneNum,@Adress)"; comm.Parameters.AddWithValue("UserId", contact.UserId); comm.Parameters.AddWithValue("FirstN", contact.FirstN); comm.Parameters.AddWithValue("LastN", contact.LastN); comm.Parameters.AddWithValue("MiddleN", contact.MiddleN); comm.Parameters.AddWithValue("PhoneNum", contact.PhoneNum); comm.Parameters.AddWithValue("Adress", contact.Adress); comm.CommandType = CommandType.Text; conn.Open(); return comm.ExecuteNonQuery(); } catch (Exception) { throw; } finally { if (conn != null) { conn.Close(); } } }
//Метод для отримання всіх контактів поточного користувача public List<Contact> GetAllContacts(short userId) { List<Contact> userContacts = new List<Contact>(); try { comm.CommandText = "SELECT * FROM Contacts WHERE UserId = @UserId"; comm.Parameters.AddWithValue("UserId", userId); comm.CommandType = CommandType.Text; conn.Open(); SqlDataReader reader = comm.ExecuteReader(); while (reader.Read()) { Contact contact = new Contact(); contact.ContactId = (short) reader[0]; contact.UserId = (short)reader[1]; contact.FirstN = reader[2].ToString(); contact.LastN = reader[3].ToString(); contact.MiddleN = reader[4].ToString(); contact.PhoneNum = reader[5].ToString(); contact.Adress = reader[6].ToString(); userContacts.Add(contact); } return userContacts; } catch (Exception) { throw; } finally { if (conn != null) { conn.Close(); } } }
//Метод для зміни записів в БД public int UpdateContact(Contact contact) { try { comm.CommandText = "UPDATE Contacts SET UserId = @UserId,FirstN = @FirstN,LastN = @LastN, MiddleN = @MiddleN,PhoneNum = @PhoneNum, Adress = Adress WHERE ContactId = @ContactId"; comm.Parameters.AddWithValue("ContactId", contact.ContactId); comm.Parameters.AddWithValue("UserId", contact.UserId); comm.Parameters.AddWithValue("FirstN", contact.FirstN); comm.Parameters.AddWithValue("LastN", contact.LastN); comm.Parameters.AddWithValue("MiddleN", contact.MiddleN); comm.Parameters.AddWithValue("PhoneNum", contact.PhoneNum); comm.Parameters.AddWithValue("Adress", contact.Adress); comm.CommandType = CommandType.Text; conn.Open(); return comm.ExecuteNonQuery(); } catch (Exception) { throw; } finally { if (conn != null) { conn.Close(); } } }