0Pricing
C# Academy · Lesson

Working with Databases

Connect to databases and perform CRUD operations using C#.

Working with Databases is a free C# Academy lesson on CoddyKit — lesson 4 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 5 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Working with Databases

Welcome to the next lesson! In this lesson, you’ll learn how to interact with databases in C#. We’ll cover establishing connections, executing queries, and managing data. Let’s get started!

Working with Databases — illustration 1

2

What is a Database?

A database is an organized collection of data that can be accessed, managed, and updated. Databases are commonly used to store and retrieve information in applications.

Key Point: Relational databases, such as SQL Server and MySQL, organize data into tables with rows and columns.

3

Setting Up a Connection

To connect to a database, use the SqlConnection class from the System.Data.SqlClient namespace. Example:

Tip: Replace your_server and your_database with your actual server and database names.

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string connectionString = "Data Source=your_server;Initial Catalog=your_database;Integrated Security=True";

        using (SqlConnection connection = new SqlConnection(connectionString)) {
            connection.Open();
            Console.WriteLine("Database connection established.");
        }
    }
}

4

Executing SQL Commands

To execute SQL commands, use the SqlCommand class. Example:

Key Point: Use ExecuteNonQuery for commands that modify data (e.g., INSERT, UPDATE, DELETE).

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string connectionString = "Data Source=your_server;Initial Catalog=your_database;Integrated Security=True";

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

            string query = "INSERT INTO Users (Name, Age) VALUES ('Alice', 25)";
            SqlCommand command = new SqlCommand(query, connection);

            int rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine($"{rowsAffected} row(s) inserted.");
        }
    }
}

5

Reading Data

To read data from a database, use the SqlDataReader class. Example:

Key Point: Always close the SqlDataReader after reading data.

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string connectionString = "your_connection_string_here";

        using (SqlConnection connection = new SqlConnection(connectionString)) {
            connection.Open();
            string query = "SELECT Id, Name FROM Users";

            using (SqlCommand command = new SqlCommand(query, connection)) {
                using (SqlDataReader reader = command.ExecuteReader()) {
                    while (reader.Read()) {
                        Console.WriteLine($"ID: {reader["Id"]}, Name: {reader["Name"]}");
                    }
                }
            }
        }
    }
}

6

Inserting Data

To insert data into a database, use the SqlCommand class with an INSERT query. Example:

Tip: Use parameters for dynamic values to prevent SQL injection.

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string connectionString = "your_connection_string_here";

        using (SqlConnection connection = new SqlConnection(connectionString)) {
            connection.Open();
            string query = "INSERT INTO Users (Name, Age) VALUES (@Name, @Age)";

            using (SqlCommand command = new SqlCommand(query, connection)) {
                command.Parameters.AddWithValue("@Name", "Alice");
                command.Parameters.AddWithValue("@Age", 25);
                int rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine(rowsAffected + " row(s) inserted.");
            }
        }
    }
}

7

Updating and Deleting Data

Use the UPDATE and DELETE SQL commands to modify or remove data. Example:

using System;
using System.Data.SqlClient;

class Program {
    static void Main() {
        string connectionString = "your_connection_string_here";

        using (SqlConnection connection = new SqlConnection(connectionString)) {
            connection.Open();
            string updateQuery = "UPDATE Users SET Age = @Age WHERE Name = @Name";
            string deleteQuery = "DELETE FROM Users WHERE Name = @Name";

            using (SqlCommand command = new SqlCommand(updateQuery, connection)) {
                command.Parameters.AddWithValue("@Name", "Alice");
                command.Parameters.AddWithValue("@Age", 26);
                command.ExecuteNonQuery();
                Console.WriteLine("Data updated.");
            }

            using (SqlCommand command = new SqlCommand(deleteQuery, connection)) {
                command.Parameters.AddWithValue("@Name", "Alice");
                command.ExecuteNonQuery();
                Console.WriteLine("Data deleted.");
            }
        }
    }
}

8

9

Best Practices for Database Operations

Here are some best practices:

  • Always use parameterized queries to prevent SQL injection.
  • Close database connections promptly using the using statement.
  • Log database errors for debugging and monitoring purposes.

Tip: Use stored procedures for complex queries to enhance performance and maintainability.

10

Great Job!

Congratulations! You’ve learned how to connect to a database, run queries, and manipulate data using C#. In the next lesson, we’ll explore LINQ for powerful and intuitive data queries. Let’s keep coding!

Working with Databases — illustration 10

Frequently asked questions

Is the “Working with Databases” lesson free?

Yes — the full text of “Working with Databases” is free to read here on the web, and the C# Academy course includes 5 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Working with Databases”?

Connect to databases and perform CRUD operations using C#. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 5, so you can start here or from the beginning and move at your own pace.

How long does the “Working with Databases” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading and Writing Files
  2. Working with JSON and XML
  3. Understanding Exception Handling
  4. Working with Databases
  5. Using LINQ for Data Queries
← Back to C# Academy