A DataReader is a lean, mean access method that returns
results as soon as they are available, rather than waiting for the whole of the
query to be populated into a DataSet. This can boost your application performance
quite dramatically and, once you get used to the methodology, can be quite
elegant in and of itself.
To get first employee information we are waiting until the whole
data is filled in the dataset.
Listing 15
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter dta = new SqlDataAdapter
("select * from EmpTable;", conn);
DataSet ds = new DataSet();
dta.Fill(ds);
string strFirstEmpInfo = ds.Tables[0].Rows[0][0].ToString();
Now using a datareader once the required record is fetched,
collecting other results is no way required. This can boost your application
performance.
Listing 16
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = new SqlCommand("select * from EmpTable", conn);
comm.Connection.Open();
SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
string strFirstEmpInfo;
while(dr.Read())
{
strFirstEmpInfo = dr.GetString(0);
break;
}
dr.Close();
conn.Close();
Not only can we inspect as we go, but the DataReader only
stores one result at a time on the client. This results in a significant
reduction in memory usage and system resources when compared to the DataSet,
where the whole query is stored.