private void UpdateButton_Click(object sender, RoutedEventArgs e) { if (MainGrid.SelectedItem == null) { return; } var detailWindow = new EmployeeDetailWindow(MainGrid.SelectedItem as Employee); if (detailWindow.ShowDialog() != true) { return; } var updated = detailWindow.Model; using (var conn = new SqlConnection(CONNECTION_STRING)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = $" UPDATE Employees" + $" SET Name='{updated.Name}', Productivity={updated.Productivity.ToString(CultureInfo.InvariantCulture)}, TotalBonus={updated.TotalBonus}" + $" WHERE Id={updated.Id};"; cmd.ExecuteNonQuery(); } } MainGrid.ItemsSource = ReadEmployeesFromDb(); }
private void NewButton_Click(object sender, RoutedEventArgs e) { var detailWindow = new EmployeeDetailWindow(); if (detailWindow.ShowDialog() != true) { return; } var newEmployee = detailWindow.Model; using (var conn = new SqlConnection(CONNECTION_STRING)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; // Questo modo di costruire le stringhe è SBAGLIATO, // perché concatenare i valori a mano // espone l'applicativo ad attacchi di tipo SQL INJECTION: //cmd.CommandText = // $" INSERT INTO Employees" + // $" (Name, Productivity, TotalBonus)" + // $" values" + // $" ('{newEmployee.Name}', {newEmployee.Productivity.ToString(CultureInfo.InvariantCulture)}, {newEmployee.TotalBonus})"; cmd.CommandText = $" INSERT INTO Employees" + $" (Name, Productivity, TotalBonus)" + $" values" + $" (@Name, @Productivity, @TotalBonus)"; cmd.Parameters.AddWithValue("@Name", newEmployee.Name); cmd.Parameters.AddWithValue("@Productivity", newEmployee.Productivity.ToString(CultureInfo.InvariantCulture)); cmd.Parameters.AddWithValue("@TotalBonus", newEmployee.TotalBonus); cmd.ExecuteNonQuery(); } } MainGrid.ItemsSource = ReadEmployeesFromDb(); }