Insert / Delete / Update — Full Example
Intermediate
25 min read
Lesson 3 of 5
This lesson wires up all three operations against the Students table using parameterized commands (never string concatenation — that's how SQL injection happens).
A reusable repository class
using Microsoft.Data.SqlClient;
public class StudentRepository
{
private readonly string _connectionString;
public StudentRepository(string connectionString)
{
_connectionString = connectionString;
}
public void AddStudent(string firstName, string lastName, string email)
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = new SqlCommand(
"INSERT INTO Students (FirstName, LastName, Email) VALUES (@FirstName, @LastName, @Email)",
connection);
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@Email", email);
command.ExecuteNonQuery();
}
public void UpdateStudentEmail(int studentId, string newEmail)
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = new SqlCommand(
"UPDATE Students SET Email = @Email WHERE StudentId = @StudentId",
connection);
command.Parameters.AddWithValue("@Email", newEmail);
command.Parameters.AddWithValue("@StudentId", studentId);
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 0)
throw new InvalidOperationException($"No student found with Id {studentId}");
}
public void DeleteStudent(int studentId)
{
using var connection = new SqlConnection(_connectionString);
connection.Open();
using var command = new SqlCommand(
"DELETE FROM Students WHERE StudentId = @StudentId",
connection);
command.Parameters.AddWithValue("@StudentId", studentId);
command.ExecuteNonQuery();
}
}
Using it
var repo = new StudentRepository(connectionString);
repo.AddStudent("Layla", "Ibrahim", "layla.i@example.com");
repo.UpdateStudentEmail(1, "ali.updated@example.com");
repo.DeleteStudent(3);
Why @Parameters instead of string interpolation?
// NEVER DO THIS — vulnerable to SQL injection:
var command = new SqlCommand($"DELETE FROM Students WHERE StudentId = {studentId}", connection);
// ALWAYS DO THIS instead — parameters are sent separately from the query text:
var command = new SqlCommand("DELETE FROM Students WHERE StudentId = @StudentId", connection);
command.Parameters.AddWithValue("@StudentId", studentId);
Key Takeaway
Always use parameterized commands to prevent SQL injection. Never concatenate user input into SQL strings.