CRUD Operations - potatoscript/csharp GitHub Wiki
π₯ CRUD Operations (Create, Read, Update, Delete) in C# π₯
π What is CRUD?
CRUD stands for:
- π₯ C β Create (Add new data)
- π₯ R β Read (Retrieve or view data)
- π₯ U β Update (Modify existing data)
- π₯ D β Delete (Remove data)
Imagine running a potato farm where you:
- Create β Add new types of potatoes to your storage. π₯π±
- Read β Check which potatoes are available. ππ₯
- Update β Change the potato price or update its quality. π οΈπ₯
- Delete β Remove the rotten or expired potatoes. βπ₯
π― How Does CRUD Work in C#?
To perform CRUD operations in C#, we follow these steps:
- Connect to the database π‘
- Write SQL queries π
- Execute SQL commands β
- Process the results π
π Required Setup
Before starting CRUD operations, make sure you:
β
Install the required database provider (SQL Server, MySQL, or SQLite).
β
Include necessary namespaces in your code.
using System;
using System.Data.SqlClient; // For SQL Server
using MySql.Data.MySqlClient; // For MySQL
using System.Data.SQLite; // For SQLite
π₯ Setting Up the Database
Letβs create a table called Potatoes in the database. It will have the following fields:
Field Name | Data Type | Description |
---|---|---|
Id |
int |
Unique ID for each potato |
Name |
varchar |
Name of the potato |
Type |
varchar |
Type of the potato |
PricePerKg |
decimal |
Price per kg |
π― Create Table SQL Query:
CREATE TABLE Potatoes (
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(50),
Type NVARCHAR(50),
PricePerKg DECIMAL(5,2)
);
π― Connection String
Hereβs a sample connection string to connect to SQL Server:
string connectionString = @"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;";
β Explanation:
Server
β Where the database is located.Database
β Name of the database.User Id
β Username to access the database.Password
β Password for the user.
π₯ C β Create (Insert New Data)
To add a new potato to the database, we use the INSERT
SQL query.
π§ Example:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = @"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("π₯ Connected to the database!");
// Insert query to add a new potato
string query = "INSERT INTO Potatoes (Name, Type, PricePerKg) VALUES (@Name, @Type, @PricePerKg)";
// Create command and add parameters
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", "Golden Potato");
command.Parameters.AddWithValue("@Type", "Yukon Gold");
command.Parameters.AddWithValue("@PricePerKg", 3.5);
// Execute query
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"β
{rowsAffected} row(s) inserted successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"β οΈ Error: {ex.Message}");
}
}
}
}
π Output:
π₯ Connected to the database!
β
1 row(s) inserted successfully!
π R β Read (Retrieve Data)
To check available potatoes, we use the SELECT
SQL query.
π§ Example:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = @"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("π₯ Connected to the database!");
// Select query to read all potatoes
string query = "SELECT Id, Name, Type, PricePerKg FROM Potatoes";
// Create command
SqlCommand command = new SqlCommand(query, connection);
// Execute query and read data
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"π₯ Id: {reader["Id"]}, Name: {reader["Name"]}, Type: {reader["Type"]}, Price: {reader["PricePerKg"]} per kg");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"β οΈ Error: {ex.Message}");
}
}
}
}
π Output:
π₯ Connected to the database!
π₯ Id: 1, Name: Golden Potato, Type: Yukon Gold, Price: 3.5 per kg
π οΈ U β Update (Modify Data)
To update the price of a potato, we use the UPDATE
SQL query.
π§ Example:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = @"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("π₯ Connected to the database!");
// Update query to change the price
string query = "UPDATE Potatoes SET PricePerKg = @Price WHERE Name = @Name";
// Create command and add parameters
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Price", 4.0);
command.Parameters.AddWithValue("@Name", "Golden Potato");
// Execute query
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"β
{rowsAffected} row(s) updated successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"β οΈ Error: {ex.Message}");
}
}
}
}
π Output:
π₯ Connected to the database!
β
1 row(s) updated successfully!
β D β Delete (Remove Data)
To remove rotten potatoes from the database, we use the DELETE
SQL query.
π§ Example:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = @"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("π₯ Connected to the database!");
// Delete query to remove a potato
string query = "DELETE FROM Potatoes WHERE Name = @Name";
// Create command and add parameters
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", "Golden Potato");
// Execute query
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"β
{rowsAffected} row(s) deleted successfully!");
}
catch (Exception ex)
{
Console.WriteLine($"β οΈ Error: {ex.Message}");
}
}
}
}
π Output:
π₯ Connected to the database!
β
1 row(s) deleted successfully!