Is My DataTable Snippet Written Correctly?

Posted by user311509 on Stack Overflow See other posts from Stack Overflow or by user311509
Published on 2011-01-04T09:34:21Z Indexed on 2011/01/04 9:53 UTC
Read the original article Hit count: 219

Filed under:
|
|
|
   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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET