Is My DataTable Snippet Written Correctly?
- by user311509
public static DataTable GetDataTable(SqlCommand sqlCmd)
{
DataTable tblMyTable = new DataTable();
DataSet myDataSet = new DataSet();
try
{
//1. Create connection
mSqlConnection = new SqlConnection(mStrConnection);
//2. Open connection
mSqlConnection.Open();
mSqlCommand = new SqlCommand();
mSqlCommand = sqlCmd;
//3. Assign Connection
mSqlCommand.Connection = mSqlConnection;
//4. Create/Set DataAdapter
mSqlDataAdapter = new SqlDataAdapter();
mSqlDataAdapter.SelectCommand = mSqlCommand;
//5. Populate DataSet
mSqlDataAdapter.Fill(myDataSet, "DataSet");
tblMyTable = myDataSet.Tables[0];
}
catch (Exception ex)
{
}
finally
{
//6. Clear objects
if ((mSqlDataAdapter != null))
{
mSqlDataAdapter.Dispose();
}
if ((mSqlCommand != null))
{
mSqlCommand.Dispose();
}
if ((mSqlConnection != null))
{
mSqlConnection.Close();
mSqlConnection.Dispose();
}
}
//7. Return DataSet
return tblMyTable;
}
I use the above code to return
records from database.
The above snippet would run in web
application which expected to have
around 5000 visitors daily.
The records returned reach 20,000 or
over.
The returned records are viewed
(read-only) in paged GridView.
Would it be better to use DataReader instead of DataTable?
NOTE: two columns in the GridView are hyperlinked.