Wednesday, July 29, 2009

Loading Data by Generic List using stored procedure with DataTable and DataReader

In the above code snipeet, I have two method called LoadDataThroughDataReader and LoadDataThroughDataTable. In both method, I have declared a variable for List that is filled with the Person records returned from the database. The first method LoadDataThroughDataReader use
cmd.ExecuteReader() method to get the SqlDataReader and read through all the records in the reader and add the Person object into the List.


The second method is slightly different and use DataTable instead of DataReader to fetch data from database, loop through all the rows of the DataTable and add Person objects into the list.

You may wonder why these two methods when both are doing the same thing. I prefer using DataReader when I have lesser amount of data from the database and loop through because DataReader expect live connection when it loops through all the records. For large amount of data, it may be a bottleneck for the database to keep the connection alive and loop through. So for large amount of data I prefer to fill the DataTable, close the database connection and then loop through all the records do the required operation.

public List LoadThroughDataReader()
{
var list = new List();
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("LoadAll", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Person p = new Person()
{
Age = reader.GetInt32(reader.GetOrdinal("Age")),
FirstName = reader.GetString(reader.GetOrdinal("FirstName")),
LastName = reader.GetString(reader.GetOrdinal("LastName"))
};
list.Add(p);
}
}
conn.Close();
}
return list;
}
}

public List LoadThroughDataTable()
{
var list = new List();
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("LoadAll", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
conn.Open();
// open the connection
ad.Fill(table);
conn.Close();
// close the connection
// loop through all rows
foreach (DataRow row in table.Rows)
{
Person p = new Person()
{
Age = int.Parse(row["Age"].ToString()),
FirstName = row["FirstName"].ToString(),
LastName = row["LastName"].ToString()
};
list.Add(p);
}
}
}
return list;
}
}

No comments:

Post a Comment