ADO.NET

ADO.NET Projects

ADO.NET Project 1

ADO.NET Examples

Examples

DataReader
Previous Home Next

The DataReader provides a read-only, forward-only stream of results from a database query or stored procedure and we can use a DataReader if it is desirable,and possible, to keep the connection to the database open while data is being processed.A DataReader is a lightweight object which provides read-only, forward-only data in a very fast and efficient way . DataReader is efficient than using a DataAdapter but it is limited and Data access with DataReader is read-only, i.e, you cannot make any changes (update) to data and forward-only, i.e we cannot go back to the previous record which was accessed.

DataReader requires the exclusive use of an active connection for the entire time if it is in existence and we instantiate a DataReader by calling a Command object's ExecuteReader command. When the DataReader is first returned it is positioned before the first record of the result set. To making the first record available we need to call the Read method and If a record is exist, the Read method moves the DataReader for next record and returns True and If a record is not available then the Read method returns False. we can use a While Loop to iterate through the records with the Read method.

Example of DataReader
using System;
using System.Data;
using System.Data.SqlClient;
public class empnamereader {
public static void Main() {
SqlConnection con = new SqlConnection(
"server=(local)\mycomputer;database=emp;trusted_connection=yes"
);
string s = "SELECT * FROM emp";
con.Open();
sqlcommand cmd=new sqlcommand(s, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
Console.WriteLine(sdr["empname"] );
}
con.Close();
}
}

 

Data Retrieval Methods of the DataReader Object

Method Field Type
GetBoolean() Bool
GetByte() Byte
GetChar() Char
GetDateTime() DateTime
GetDecimal() Decimal
GetDouble() Double
GetFloat() Float
GetGuid() Guid
GetInt16() Int16
GetInt32() Int32
GetInt64() Int64
GetString() String

Differences between “DataSet” and “DataReader

DataSet DataReader
DataSet object can contain multiple rowsets from the same data source as well as from the relationships between them. DataReader provides forward-only and read-only access to data.
Dataset is a disconnected architecture. Datareader is connected architecture.
Dataset can persist data. Datareader can not persist data.
A DataSet is well suited for data that needs to be retrieved from multiple tables. It has live connection while reading data
DatsSet is slower than DataReader ,Due to overhead. Speed performance is better in DataReader

Limitations of the DataReader

There is not possible to sort, filter, or manipulate the data while using a DataReader, since it is read-only and forward-only.

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback:
>