Modifying Data with ADO.NET

This document explains how to modify data in a data source using ADO.NET. ADO.NET provides a rich set of objects for interacting with data, including commands for inserting, updating, and deleting records.

Core Concepts

Modifying data typically involves constructing SQL statements (like INSERT, UPDATE, DELETE) and executing them against the data source. ADO.NET facilitates this through the Command object and its derived classes (e.g., SqlCommand for SQL Server).

Using the Command Object

The Command object represents a SQL statement or stored procedure to be executed against a data source. You can create a command and associate it with a connection.

Example: Inserting a Record


using System.Data.SqlClient;

// Assume 'connectionString' is properly defined
string connectionString = "Your_Connection_String_Here";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string insertQuery = "INSERT INTO Customers (CustomerID, CompanyName, ContactName) VALUES (@CustomerID, @CompanyName, @ContactName)";

    using (SqlCommand command = new SqlCommand(insertQuery, connection))
    {
        // Using parameters to prevent SQL injection
        command.Parameters.AddWithValue("@CustomerID", "ALFKI");
        command.Parameters.AddWithValue("@CompanyName", "Alfreds Futterkiste");
        command.Parameters.AddWithValue("@ContactName", "Maria Anders");

        int rowsAffected = command.ExecuteNonQuery(); // Execute the insert command

        Console.WriteLine($"{rowsAffected} row(s) inserted.");
    }
}
            

ExecuteNonQuery() Method

The ExecuteNonQuery() method is used to execute Transact-SQL statements that do not return a result set, such as INSERT, UPDATE, and DELETE statements. It returns the number of rows affected by the command.

Using Parameters

It is crucial to use parameterized queries when constructing commands that include user-supplied input. This helps prevent SQL injection vulnerabilities. The Parameters collection of the Command object is used to add parameters.

Note: Always use parameterized queries to sanitize input and protect your application from SQL injection attacks. Avoid directly concatenating user input into SQL strings.

Updating Data

To update existing records, you can use the UPDATE SQL statement in conjunction with the Command object and parameterized queries.

Example: Updating a Record


using System.Data.SqlClient;

string connectionString = "Your_Connection_String_Here";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string updateQuery = "UPDATE Customers SET ContactName = @NewContactName WHERE CustomerID = @CustomerID";

    using (SqlCommand command = new SqlCommand(updateQuery, connection))
    {
        command.Parameters.AddWithValue("@NewContactName", "Maria Schmidt");
        command.Parameters.AddWithValue("@CustomerID", "ALFKI");

        int rowsAffected = command.ExecuteNonQuery();

        Console.WriteLine($"{rowsAffected} row(s) updated.");
    }
}
            

Deleting Data

Similarly, deleting records is achieved using the DELETE SQL statement.

Example: Deleting a Record


using System.Data.SqlClient;

string connectionString = "Your_Connection_String_Here";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string deleteQuery = "DELETE FROM Customers WHERE CustomerID = @CustomerID";

    using (SqlCommand command = new SqlCommand(deleteQuery, connection))
    {
        command.Parameters.AddWithValue("@CustomerID", "ALFKI");

        int rowsAffected = command.ExecuteNonQuery();

        Console.WriteLine($"{rowsAffected} row(s) deleted.");
    }
}
            

Best Practices

Important: The examples provided use System.Data.SqlClient for SQL Server. ADO.NET supports other data providers (e.g., System.Data.OleDb, System.Data.OracleClient, MySql.Data.MySqlClient) with similar concepts but potentially different specific classes.