ADO.NET Tutorial

ADO.NET Introduction

ADO.NET (ActiveX Data Objects) data access करने के लिए इस्तमाल किया जाता है ये .NET Framework का एक पैकेज है, जिसका इस्तमाल हम डेटाबेस से interact करने के लिए करते है. इस पैकेज में built-in फीचर और classes है जिससे हम SQL Server, Oracle, और अन्य relational databases से connect कर पाते है अपने application को.

ADO.NET Data Providers, Connection objects, Command objects, DataReaders, और DataAdapters का इस्तमाल करता है जिससे data flow को मैनेज किया जा सके applications और database के बिच में.

ADO.NET supports both disconnected and connected data models. The disconnected model employs DataSets, which can be modified even while offline; whereas the connected model involves real-time interaction with the database via an active connection.

Data Provider

Data Provider, कई classes का एक सेट है जिसका इस्तेमाल किसी data source के साथ इंटरैक्ट करने के लिए किया जाता है। data provider में ये components होते हैं:

मुख्य ADO.NET Data Providers ये हैं:

Example: SQL Server Data Provider

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

class StudentDataApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string query = "SELECT * FROM Students";
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine($"ID: {reader["StudentId"]}, Name: {reader["StudentName"]}");
            }
        }
    }
}

इस उदाहरण में, SqlConnection SQL Server से एक कनेक्शन स्थापित करता है, और SqlCommand ऑब्जेक्ट का उपयोग SQL क्वेरी को execute करने के लिए किया जाता है। SqlDataReader डेटाबेस से डेटा को केवल आगे की दिशा में (forward-only manner) retrieve करता है।

ADO.NET Data Adapter

DataAdapter ADO.NET में उपयोग किया जाने वाला एक ऑब्जेक्ट है, जिसका इस्तेमाल DataSet को populate करने और डेटा स्रोत को अपडेट करने के लिए किया जाता है। यह डेटा स्रोत और एप्लिकेशन के बीच एक सेतु (bridge) का काम करता है, जिससे disconnected mode में काम करते हुए भी डेटा को retrieve और modify करना संभव हो पाता है।

Example: Using DataAdapter

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

class StudentDataSetApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string query = "SELECT * FROM Students";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection);
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet, "Students");

            foreach (DataRow row in dataSet.Tables["Students"].Rows)
            {
                Console.WriteLine($"ID: {row["StudentId"]}, Name: {row["StudentName"]}");
            }
        }
    }
}

इस उदाहरण में, SqlDataAdapter, Employees टेबल से डेटा लेता है और उसे एक DataSet में भर देता है। DataSet के अंदर के डेटा को बदला जा सकता है, और इन बदलावों को बाद में DataAdapter के Update मेथड का इस्तेमाल करके डेटाबेस में वापस भेजा जा सकता है।

ADO.NET SQL Server कनेक्शन

ADO.NET, SQL Server Data Provider का इस्तेमाल करके SQL Server डेटाबेस के साथ इंटरैक्ट करने के लिए क्लास देता है। ADO.NET में, SqlConnection क्लास का इस्तेमाल SQL Server डेटाबेस से कनेक्शन खोलने के लिए किया जाता है। एक बार कनेक्शन बन जाने के बाद, आप डेटाबेस के साथ इंटरैक्ट करने के लिए SQL क्वेरी या स्टोर्ड प्रोसीजर चला सकते हैं।

SQL Server कनेक्शन में शामिल मुख्य क्लास ये हैं:

The primary classes involved in SQL Server connections are:

Example: SQL Server Connection

The following example demonstrates how to establish a connection to a SQL Server database using SqlConnection, execute a simple SQL query, and retrieve the results using SqlDataReader.

using System;
using System.Data.SqlClient;

class StudentReaderApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            string query = "SELECT StudentName, Course FROM Students";
            
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine($"{reader["StudentName"]}, {reader["Course"]}");
            }
        }
    }
}

इस उदाहरण में, कनेक्शन स्ट्रिंग में Server, Database, User ID और Password शामिल हैं, जो SQL Server इंस्टेंस से कनेक्ट करने के लिए ज़रूरी हैं। कनेक्शन एक SqlConnection ऑब्जेक्ट का इस्तेमाल करके खोला जाता है, और क्वेरी एक SqlCommand का इस्तेमाल करके चलाई जाती है। नतीजों को एक SqlDataReader का इस्तेमाल करके पढ़ा जाता है।

SQL Server कनेक्शन में Error Handling

ADO.NET और SQL Server कनेक्शन के साथ काम करते समय एक्सेप्शन को संभालना बहुत ज़रूरी है। आप कनेक्शन से जुड़ी समस्याओं, गलत क्वेरी या उपलब्ध न होने वाले डेटाबेस जैसे एक्सेप्शन को पकड़ने के लिए try-catch ब्लॉक का इस्तेमाल कर सकते हैं।

using System;
using System.Data.SqlClient;

class StudentExceptionApp
{
    static void Main()
    {
        try
        {
            string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
            
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string query = "SELECT * FROM Students";
                SqlCommand command = new SqlCommand(query, connection);
                SqlDataReader reader = command.ExecuteReader();
                
                while (reader.Read())
                {
                    Console.WriteLine($"ID: {reader["StudentId"]}, Name: {reader["StudentName"]}");
                }
            }
        }
        catch (SqlException ex)
        {
            Console.WriteLine("Database error: " + ex.Message);
        }
    }
}

इस उदाहरण में, यदि कोई कनेक्शन एरर या SQL क्वेरी से संबंधित कोई समस्या आती है, तो SqlException को पकड़ा जाएगा, और एक एरर मैसेज दिखाया जाएगा। डेटाबेस के साथ काम करते समय एरर हैंडलिंग को शामिल करना हमेशा एक अच्छा तरीका होता है, ताकि क्रैश से बचा जा सके और यूज़र को सही फ़ीडबैक दिया जा सके।

ADO.NET SQL Server कनेक्शन के लिए सबसे अच्छे तरीके

जब आप ADO.NET SQL Server कनेक्शन के साथ काम कर रहे हों, तो यहाँ कुछ सबसे अच्छे तरीके दिए गए हैं जिनका पालन करना चाहिए:

ADO.NET Command

ADO.NET में, SqlCommand क्लास का उपयोग SQL Server डेटाबेस पर SQL क्वेरी या स्टोर्ड प्रोसीजर को एग्ज़ीक्यूट करने के लिए किया जाता है। इसका उपयोग SELECT, INSERT, UPDATE, और DELETE ऑपरेशन के लिए किया जा सकता है। SQL कमांड को एग्ज़ीक्यूट करने के लिए, इसे डेटाबेस से एक खुले हुए कनेक्शन की आवश्यकता होती है।

एक SqlCommand को SQL क्वेरी स्ट्रिंग और एक कनेक्शन ऑब्जेक्ट के साथ इनिशियलाइज़ किया जा सकता है। एक बार जब कमांड सेट हो जाता है, तो आप इसे ExecuteReader, ExecuteNonQuery, या ExecuteScalar जैसे तरीकों का उपयोग करके एग्ज़ीक्यूट कर सकते हैं।

SqlCommand Example

using System;
using System.Data.SqlClient;

class StudentInsertApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            string query = "INSERT INTO Students (StudentName, Course) VALUES (@studentName, @course)";
            
            SqlCommand command = new SqlCommand(query, connection);
            
            command.Parameters.AddWithValue("@studentName", "Rahul Sharma");
            command.Parameters.AddWithValue("@course", "BCA");
            
            int result = command.ExecuteNonQuery();
            
            if (result > 0)
            {
                Console.WriteLine("Data inserted successfully!");
            }
        }
    }
}

इस उदाहरण में, हम SqlCommand बनाते हैं ताकि Employees टेबल में डेटा डाला जा सके। SQL injection हमलों से बचने के लिए पैरामीटर जोड़े जाते हैं। यहाँ ExecuteNonQuery मेथड का इस्तेमाल किया गया है क्योंकि यह कोई result set नहीं लौटाता, बल्कि प्रभावित हुए rows की संख्या बताता है।

ADO.NET DataReader

SqlDataReader क्लास का इस्तेमाल SQL Server डेटाबेस से forward-only डेटा स्ट्रीम को retrieve करने के लिए किया जाता है। यह बड़े datasets को पढ़ने के लिए बहुत प्रभावी है, क्योंकि यह डेटा को सीधे डेटाबेस से लेता है और पूरी dataset को मेमोरी में buffer नहीं करता।

SqlCommand की ExecuteReader मेथड एक SqlDataReader ऑब्जेक्ट लौटाती है, जिसे आप Read() मेथड का इस्तेमाल करके एक-एक row के डेटा तक पहुँचने के लिए iterate कर सकते हैं।

SqlDataReader Example

using System;
using System.Data.SqlClient;

class StudentDisplayApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            string query = "SELECT StudentName, Course FROM Students";
            
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine($"{reader["StudentName"]}, {reader["Course"]}");
            }
        }
    }
}

इस उदाहरण में, एक SqlCommand का उपयोग एक SELECT क्वेरी को चलाने के लिए किया जाता है, जो Employees टेबल से कर्मचारियों के नाम और जॉब टाइटल प्राप्त करती है। क्वेरी द्वारा लौटाए गए डेटा को केवल आगे की दिशा में (forward-only manner) पढ़ने के लिए एक SqlDataReader ऑब्जेक्ट का उपयोग किया जाता है।

Read() मेथड रीडर को अगली पंक्ति पर ले जाता है, और आप उस पंक्ति के भीतर के डेटा को कॉलम नामों या कॉलम इंडेक्स का उपयोग करके एक्सेस कर सकते हैं। यह लूप तब तक चलता रहता है जब तक सभी पंक्तियाँ पढ़ी नहीं जातीं।

ADO.NET कमांड के प्रकार

SqlCommand आपको विभिन्न प्रकार के SQL कमांड चलाने की अनुमति देता है:

ADO.NET कमांड पैरामीटर्स

SqlCommand SQL क्वेरी के भीतर डेटा को सुरक्षित रूप से पास करने के लिए पैरामीटर्स के उपयोग का समर्थन करता है। SQL इंजेक्शन हमलों को रोकने के लिए यह अत्यंत महत्वपूर्ण है। आप AddWithValue मेथड या SqlCommand द्वारा प्रदान किए गए अन्य पैरामीटर-संबंधित मेथड्स का उपयोग करके पैरामीटर्स जोड़ सकते हैं।

using System;
using System.Data.SqlClient;

class StudentFilterApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            string query = "SELECT StudentName FROM Students WHERE Course = @course";
            SqlCommand command = new SqlCommand(query, connection);
            
            command.Parameters.AddWithValue("@course", "BCA");
            
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine(reader["StudentName"]);
            }
        }
    }
}

इस उदाहरण में, SQL क्वेरी में @jobTitle पैरामीटर जोड़ा गया है ताकि मान को सुरक्षित रूप से क्वेरी तक पहुँचाया जा सके। यह उपयोगकर्ता के इनपुट को सीधे क्वेरी में डाले जाने से रोकता है, जिससे अन्यथा SQL इंजेक्शन की कमज़ोरियाँ पैदा हो सकती हैं।

ADO.NET DataSet

ADO.NET में, DataSet क्लास डेटा का एक इन-मेमोरी कैश है जिसका उपयोग डिस्कनेक्टेड डेटा के साथ काम करने के लिए किया जा सकता है। यह आपको डेटा की कई तालिकाओं और उनके संबंधों को मेमोरी में संग्रहीत करने की सुविधा देता है।

DataSet सीधे डेटाबेस से जुड़ा नहीं होता है। यह डेटाबेस से प्राप्त डेटा की प्रतियाँ अपने पास रखता है, जिसका अर्थ है कि इसे स्थानीय रूप से संशोधित किया जा सकता है; डेटाबेस तब तक अप्रभावित रहता है जब तक कि परिवर्तन स्पष्ट रूप से वापस उसमें लिख नहीं दिए जाते। यह विशेष रूप से तब उपयोगी होता है जब आप ऑफ़लाइन या डिस्कनेक्टेड डेटा के साथ काम कर रहे होते हैं।

DataSet Example

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

class StudentDataSetDisplay
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            DataSet dataSet = new DataSet();
            connection.Open();
            
            string query = "SELECT StudentName, Course FROM Students";

            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
            adapter.Fill(dataSet, "Students");

            DataTable studentTable = dataSet.Tables["Students"];
            
            foreach (DataRow row in studentTable.Rows)
            {
                Console.WriteLine($"{row["StudentName"]}, {row["Course"]}");
            }
        }
    }
}

In this example, a DataSet is created to store data from the Employees table. A SqlDataAdapter is used to retrieve data from the database and fill the DataSet. The data is then accessed and printed out from the DataTable inside the DataSet.

The DataSet allows for complex data structures with multiple related tables, making it easier to manage and work with data in an offline manner.

ADO.NET DataAdapter

The SqlDataAdapter serves as a bridge between the DataSet and the database. It is responsible for retrieving data from the database and filling the DataSet with that data. Additionally, it can be used to update the database with any changes made to the DataSet.

The DataAdapter provides methods such as Fill to load data into a DataSet, and Update to propagate changes from the DataSet back to the database.

DataAdapter Example

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

class StudentUpdateApp
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            DataSet dataSet = new DataSet();

            SqlDataAdapter adapter = new SqlDataAdapter("SELECT StudentName, Course FROM Students", connection);

            adapter.Fill(dataSet, "Students");

            Console.WriteLine("Original Data:");
            foreach (DataRow row in dataSet.Tables["Students"].Rows)
            {
                Console.WriteLine($"{row["StudentName"]}, {row["Course"]}");
            }

            dataSet.Tables["Students"].Rows[0]["Course"] = "MCA";

            SqlCommand updateCommand = new SqlCommand("UPDATE Students SET Course = @course WHERE StudentName = @studentName", connection);
            updateCommand.Parameters.Add("@course", SqlDbType.VarChar, 50, "Course");
            updateCommand.Parameters.Add("@studentName", SqlDbType.VarChar, 50, "StudentName");

            adapter.UpdateCommand = updateCommand;

            connection.Open();
            adapter.Update(dataSet, "Students");

            Console.WriteLine("\nData after update:");
            foreach (DataRow row in dataSet.Tables["Students"].Rows)
            {
                Console.WriteLine($"{row["StudentName"]}, {row["Course"]}");
            }
        }
    }
}

In this example, we first use the SqlDataAdapter to load data from the Employees table into a DataSet. We then modify the DataSet by changing the JobTitle of the first employee.

After modifying the DataSet, we create an UpdateCommand and associate it with the SqlDataAdapter. The Update method is used to send the changes back to the database. This is an efficient way to manage changes in data and synchronize the local changes with the database.

ADO.NET DataSet Methods

The DataSet class provides several useful methods for manipulating and working with data:

The DataSet class is very powerful, allowing for complex data manipulation and offline data management. You can add, remove, and modify tables and rows, and then use the DataAdapter to push the changes back to the database.

ADO.NET DataTables

A DataTable is a fundamental object in ADO.NET that represents a single table of in-memory data. You can manipulate a DataTable by adding, deleting, or updating rows of data, and it supports constraints, relationships, and indexing.

DataTable is part of the DataSet class, but it can be used independently. It represents one table of data and is an excellent way to store and manipulate tabular data before committing changes back to the database.

DataTable Example

using System;
using System.Data;

class StudentDataTableApp
{
    static void Main()
    {
        DataTable dataTable = new DataTable("Students");

        dataTable.Columns.Add("StudentID", typeof(int));
        dataTable.Columns.Add("StudentName", typeof(string));
        dataTable.Columns.Add("Course", typeof(string));

        dataTable.Rows.Add(1, "Rahul Sharma", "BCA");
        dataTable.Rows.Add(2, "Anjali Verma", "MCA");

        foreach (DataRow row in dataTable.Rows)
        {
            Console.WriteLine($"ID: {row["StudentID"]}, Name: {row["StudentName"]}, Course: {row["Course"]}");
        }
    }
}

In this example, we create a DataTable to represent employee data. We define the columns and add rows with employee details. The foreach loop then iterates over the rows to display the data.

You can also manipulate rows in a DataTable, such as adding new rows, updating existing ones, or deleting rows, which are very useful when dealing with offline data.

ADO.NET Web Forms Example

Web Forms (WF) is an event-driven model for building web applications in ASP.NET. It provides a way to design pages using controls such as GridView, TextBox, and Button without worrying about the underlying HTML structure.

Below is an example of how to use ADO.NET to connect to a database, retrieve data, and bind it to a GridView in a Web Forms application.

Web Forms Example with ADO.NET

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

public partial class StudentList : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT StudentID, StudentName, Course FROM Students", connection);
            DataSet dataSet = new DataSet();
            
            adapter.Fill(dataSet, "Students");

            StudentGridView.DataSource = dataSet.Tables["Students"];
            StudentGridView.DataBind();
        }
    }
}

In this Web Forms example, we use SqlDataAdapter to retrieve data from the Employees table in the database. The data is loaded into a DataSet, and then the DataSet is bound to a GridView control on the Web Form.

This approach allows you to work with data disconnected from the database and present it in an easy-to-use format on a web page. In this case, GridView is used to display employee details in a tabular form.

The code inside the Page_Load method will be executed when the page is loaded. The data retrieval, filling, and binding process happen on the server side, which sends the generated HTML to the client.

Web Form Markup (ASPX)

    < asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="True" Width="500px" >
      < Columns >
          < asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" SortExpression="EmployeeID" />
          < asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" SortExpression="EmployeeName" />
          < asp:BoundField DataField="JobTitle" HeaderText="Job Title" SortExpression="JobTitle" />
      < / Columns >
  < / asp:GridView >

In the above markup, we define a GridView control that will display the EmployeeID, EmployeeName, and JobTitle columns. The AutoGenerateColumns property is set to true, allowing the grid to automatically generate columns based on the data.

ADO.NET MVC Example

ADO.NET is commonly used in an MVC architecture for handling database operations in web applications. In an ASP.NET MVC application, ADO.NET can be used to interact with the database by retrieving and manipulating data.

Below is an example of an ADO.NET implementation in an MVC controller. This controller retrieves data from the database and passes it to a view to display the data in a table.

MVC Controller with ADO.NET Example

  using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

public class StudentController : Controller
{
    private string connectionString = "Server=localhost;Database=CollegeDB;User Id=sa;Password=1234;";

    public ActionResult Index()
    {
        DataTable students = GetStudents();
        return View(students);
    }

    private DataTable GetStudents()
    {
        DataTable dataTable = new DataTable();
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "SELECT StudentID, StudentName, Course FROM Students";
            SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
            adapter.Fill(dataTable);
        }

        return dataTable;
    }
}

In this example, the EmployeeController retrieves employee data from a SQL Server database using ADO.NET. The `GetEmployees()` method uses a SqlDataAdapter to fill a DataTable with data from the database. The data is then passed to the view.

MVC View (Razor Markup)

  @model System.Data.DataTable

  

Employee List

@foreach (DataRow row in Model.Rows) { }
Employee ID Employee Name Job Title
@row["EmployeeID"] @row["EmployeeName"] @row["JobTitle"]

The Razor view binds the DataTable passed from the controller to an HTML table. The foreach loop iterates over each row in the DataTable and renders the data in the table cells.

ADO vs ADO.NET

ADO (ActiveX Data Objects) and ADO.NET are both used to interact with databases, but they are part of different frameworks and have key differences.

ADO (ActiveX Data Objects)

ADO was introduced with ActiveX controls and was primarily used with Classic ASP and early .NET Framework applications. ADO allows access to relational data and other data sources, providing methods to execute queries, retrieve records, and manipulate data.

ADO.NET (ActiveX Data Objects .NET)

ADO.NET is an evolution of ADO designed for the .NET Framework. It provides a more powerful and flexible way to interact with databases in a disconnected fashion, allowing developers to build more scalable and efficient applications. It is commonly used in ASP.NET and WinForms applications.

Key Differences

Feature ADO ADO.NET
Data Access Active (direct connection to database) Disconnected (uses DataSet, DataTable)
XML Support No Yes, native support for XML data
Data Handling Rowset-based DataSet-based (supports multiple tables)
Performance Slower for large datasets Optimized for better performance in web and enterprise apps
Usage Used in older web technologies like Classic ASP Used in modern .NET applications like ASP.NET, WinForms, etc.