Datareader Object in

Octomber 11, 2011

DataReader offers a forward only read stream of access to the records. It is very useful in cases where we want to fetch data from the database and display in DataGrid, Label and other Webcontrols. Datareader object allows you to retrieve result of SELECT statement from command object. Datareader is faster as compared to Dataset as it only fetches data, but you can not perform update or insert operation on it. However, DataReader requires the connection with the database open until its operation is completed.

SqlDataReader sqlReader = sqlCmd.ExecuteReader();
When the ExecuteReader method in the SqlCommand Object execute, it will instantiate a SqlClient.SqlDataReader Object.

Different Datareader in
  • System.Data.SqlClient.SqlDataReader
  • System.Data.OleDb.OleDbDataReader
  • Oracle.OracleClient.OracleDataReader

Datareader Methods:

Read() :

The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .

Sample Code:

SqlConnection conn = new SqlConnection("connection_string"); SqlCommand com = new SqlCommand("select * from Table_Name", conn); conn.Open(); SqlDataReader dr = com.ExecuteReader(); while (dr.Read()) { Response.Write(dr[0].ToString());//It will access First element of the row } conn.Close();