To delete data from a database using ADO.NET, you execute a DELETE SQL command. Here's a basic example demonstrating how to delete data from a SQL Server database using ADO.NET:
Example
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void DeleteData(int id)
{
// Connection string to your database
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
// SQL query to delete data
string query = "DELETE FROM YourTable WHERE ID = @ID";
// Create a SqlConnection to connect to the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand to execute the query
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add parameters to the command to prevent SQL injection
command.Parameters.AddWithValue("@ID", id);
try
{
// Open the database connection
connection.Open();
// Execute the DELETE command
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
Console.WriteLine("Data deleted successfully.");
}
else
{
Console.WriteLine("No rows were affected. ID not found.");
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
}
}
In this example:
DeleteData
that takes the ID of the record to delete.SqlConnection
to connect to the database using a connection string.SqlCommand
with the DELETE query and add parameters to it to prevent SQL injection.ExecuteNonQuery()
method of the SqlCommand
.You can call this DeleteData
method from your ASP.NET code-behind or controller to delete data from the database. Make sure to replace placeholders like YourServer
, YourDatabase
, YourUsername
, YourPassword
, YourTable
with the actual values relevant to your database setup. Also, ensure that the id
parameter corresponds to the primary key of the record you want to delete.