i

ASP.Net A Complete Guide

DataReaders and Connected Access

It provides a systematic way to deal with connected data that completely depend on the data source. To access the data from the database, we need to call the "Command.ExecuteReader". We need to create an instance of the "Command" object and then create the "DataReader."

DataReaders are the best choice when you are working with a large amount of data because a large amount of data cannot be cached in memory.

Syntax:

SqlDataReader reader = command.ExecuteReader();

Example:

static void ReturnRow(Sqlconn conn)

{

    using (conn)

    {

        Sqlcomd comd = new Sqlcomd(

          "SELECT CategoryID, CategoryName FROM Categories;",conn);

        conn.Open();

        SqlDataread read = comd.Executeread();

        if (read.HasRows)

        {

            while (read.Read())

            {

                Console.WriteLine("{0}\t{1}", read.GetInt32(0),

                    read.GetString(1));

            }

        }

        else

        {

            Console.WriteLine("There were no rows available");

        }

        read.Close();

    }

}

DataReaders properties:

  • Connection: get the connection of SqlDataReader.

  • RecordsAffected : it returns the affected roe(inserted,deleted,modified row).

  • HasRows: it returns the value that returns if it has one or many rows.

  • IsClosed: it returns a boolean value that indicates SqlDataReader instance is closed or not.

DataReaders methods:

  • NextResult(): while reading the SQL statement, it returns the next result.

  • Close() :It used to close the SqlDataReader object.

  • Read():Used to read data from a SQL Server database.