C #
1 Introduction to C#
1.1 Overview of C#
1.2 History and Evolution of C#
1.3 NET Framework and C#
1.4 Setting Up the Development Environment
1.5 Basic Structure of a C# Program
2 C# Basics
2.1 Variables and Data Types
2.2 Operators and Expressions
2.3 Control Structures (if, else, switch)
2.4 Loops (for, while, do-while)
2.5 Arrays and Collections
3 Object-Oriented Programming in C#
3.1 Classes and Objects
3.2 Constructors and Destructors
3.3 Inheritance and Polymorphism
3.4 Encapsulation and Access Modifiers
3.5 Interfaces and Abstract Classes
3.6 Exception Handling
4 Advanced C# Concepts
4.1 Delegates and Events
4.2 Lambda Expressions
4.3 LINQ (Language Integrated Query)
4.4 Generics
4.5 Collections and Indexers
4.6 Multithreading and Concurrency
5 File Handling and Serialization
5.1 File IO Operations
5.2 Streams and ReadersWriters
5.3 Serialization and Deserialization
5.4 Working with XML and JSON
6 Windows Forms and WPF
6.1 Introduction to Windows Forms
6.2 Creating a Windows Forms Application
6.3 Controls and Event Handling
6.4 Introduction to WPF (Windows Presentation Foundation)
6.5 XAML and Data Binding
6.6 WPF Controls and Layouts
7 Database Connectivity
7.1 Introduction to ADO NET
7.2 Connecting to Databases
7.3 Executing SQL Queries
7.4 Data Adapters and DataSets
7.5 Entity Framework
8 Web Development with ASP NET
8.1 Introduction to ASP NET
8.2 Creating a Web Application
8.3 Web Forms and MVC
8.4 Handling Requests and Responses
8.5 State Management
8.6 Security in ASP NET
9 Testing and Debugging
9.1 Introduction to Unit Testing
9.2 Writing Test Cases
9.3 Debugging Techniques
9.4 Using Visual Studio Debugger
10 Deployment and Maintenance
10.1 Building and Compiling Applications
10.2 Deployment Options
10.3 Version Control Systems
10.4 Continuous Integration and Deployment
11 Exam Preparation
11.1 Overview of the Exam Structure
11.2 Sample Questions and Practice Tests
11.3 Tips for Exam Success
11.4 Review of Key Concepts
12 Additional Resources
12.1 Recommended Books and Articles
12.2 Online Tutorials and Courses
12.3 Community Forums and Support
12.4 Certification Pathways
Connecting to Databases Explained

Connecting to Databases Explained

Connecting to databases is a fundamental skill in C# for building data-driven applications. This guide will walk you through the key concepts and steps to connect to a database, perform basic operations, and handle common scenarios.

1. Key Concepts

Understanding the following key concepts is essential for connecting to databases in C#:

2. Establishing a Database Connection

To connect to a database, you need to use a connection string that contains the necessary information such as the server name, database name, and authentication details.

Example: Connecting to a SQL Server Database

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();
            Console.WriteLine("Connection successful!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Connection failed: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}

In this example, a connection string is used to create a SqlConnection object. The Open method is called to establish the connection, and the Close method is called to close it.

3. Executing SQL Commands

Once connected, you can execute SQL commands such as SELECT, INSERT, UPDATE, and DELETE. The SqlCommand class is used to execute these commands.

Example: Executing a SELECT Command

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();
            string query = "SELECT * FROM Customers";
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader["CustomerName"]);
            }

            reader.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Query execution failed: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}

In this example, a SELECT query is executed to retrieve data from the Customers table. The SqlDataReader object is used to read the data row by row.

4. Using Data Adapters

Data adapters are used to fill a dataset with data from a database and to update the database with changes made to the dataset. The SqlDataAdapter class is used for this purpose.

Example: Using a Data Adapter

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();
            string query = "SELECT * FROM Customers";
            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
            DataSet dataset = new DataSet();
            adapter.Fill(dataset, "Customers");

            foreach (DataRow row in dataset.Tables["Customers"].Rows)
            {
                Console.WriteLine(row["CustomerName"]);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Data adapter operation failed: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}

In this example, a SqlDataAdapter is used to fill a DataSet with data from the Customers table. The data is then iterated and displayed.

5. Handling Exceptions

Handling exceptions is crucial when working with databases to ensure that your application can recover from errors gracefully. Common exceptions include SqlException for SQL Server and MySqlException for MySQL.

Example: Handling Exceptions

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();
            string query = "SELECT * FROM NonExistentTable";
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader["CustomerName"]);
            }

            reader.Close();
        }
        catch (SqlException ex)
        {
            Console.WriteLine("SQL Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General Exception: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}

In this example, a SqlException is caught and handled if the query references a non-existent table.

6. Using Parameters to Prevent SQL Injection

Using parameters in SQL commands helps prevent SQL injection attacks by ensuring that user input is treated as data, not executable code.

Example: Using Parameters

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();
            string query = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@CustomerID", 1);
            SqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine(reader["CustomerName"]);
            }

            reader.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Query execution failed: " + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}

In this example, a parameter is used in the SQL query to safely pass the CustomerID value.

Conclusion

Connecting to databases in C# involves understanding key concepts such as connection strings, ADO.NET, data providers, data readers, and data adapters. By mastering these concepts and following best practices, you can build robust and secure data-driven applications. Whether you're retrieving data, executing commands, or handling exceptions, understanding how to connect to databases is essential for any C# developer.