Update Operation using SqlClient
The Update operation modifies existing records in a database. This example demonstrates updating an employee's department using SqlCommand
.
Key Topics
Update Example
Example
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;";
string query = "UPDATE Employees SET Department = @Department WHERE Name = @Name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", "John Doe");
command.Parameters.AddWithValue("@Department", "Finance");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) updated.");
}
}
}
Explanation: This example uses SqlCommand
to update the department of an employee securely using parameters.
Key Takeaways
- Use
ExecuteNonQuery
to execute update commands. - Parameters ensure secure and flexible queries.