Using ADO.NET, you can insert, update, and delete data in a database using SqlCommand
. Here's how each operation works:
Insert Data
The INSERT
SQL statement adds new records to a database table.
Example Code
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string string connectionString = "your_connection_string_here";
// SQL INSERT query
string insertQuery = "INSERT INTO YourTable (Name, Age) VALUES (@Name, @Age)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try { connection.Open();
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
// Add parameters command.Parameters.AddWithValue("@Name", "Alice");
command.Parameters.AddWithValue("@Age", 25);
// Execute the query
int rowsInserted = command.ExecuteNonQuery();
Console.WriteLine($"{rowsInserted} row(s) inserted.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Update Data
The UPDATE
SQL statement modifies existing records in a table.
Example Code
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string
string connectionString = "your_connection_string_here";
// SQL UPDATE query
string updateQuery = "UPDATE YourTable SET Age = @Age WHERE Name = @Name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try {
connection.Open();
using (SqlCommand command = new SqlCommand(updateQuery, connection))
{
// Add parameters command.Parameters.AddWithValue("@Name", "Alice");
command.Parameters.AddWithValue("@Age", 30);
// Execute the query int rowsUpdated = command.ExecuteNonQuery();
Console.WriteLine($"{rowsUpdated} row(s) updated."); } }
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Delete Data
The DELETE
SQL statement removes records from a table.
Example Code
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string
string connectionString = "your_connection_string_here";
// SQL DELETE query
string deleteQuery = "DELETE FROM YourTable WHERE Name = @Name";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try {
connection.Open();
using (SqlCommand command = new SqlCommand(deleteQuery, connection))
{
// Add parameters
command.Parameters.AddWithValue("@Name", "Alice");
// Execute the query
int rowsDeleted = command.ExecuteNonQuery();
Console.WriteLine($"{rowsDeleted} row(s) deleted.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Explanation of Common Steps
-
Connection String: Replace
"your_connection_string_here"
with your actual database connection string. -
SQL Commands:
INSERT INTO
: Adds a new row.UPDATE
: Modifies data in an existing row.DELETE FROM
: Removes one or more rows.
-
SqlConnection:
- Establish a connection to the database.
- Ensure it is closed or disposed after use by enclosing it in a
using
block.
-
SqlCommand:
- Define the SQL query to execute.
- Use the
Parameters
collection to safely pass values to prevent SQL injection.
-
ExecuteNonQuery: Executes the command and returns the number of rows affected.
Output
Insert Example:
Update Example:
Delete Example:
Best Practices
-
Use Parameters: Always use parameterized queries to avoid SQL injection attacks.
-
Transaction Management: For multiple operations, consider using transactions for data consistency.
-
Error Handling: Implement robust error handling using try-catch blocks.
-
Dispose Resources: Use
using
statements to ensure connections and commands are properly disposed of.
With these examples, you can efficiently insert, update, and delete data in a database using ADO.NET.