Solved

When to close my datareader

Posted on 2008-10-24
7
1,126 Views
Last Modified: 2013-12-17
I have inherited a C# webproject that has all of the data access code (calls stored procedures) in class files. I have added the different calls it makes below.  THis model is working fine. but now I want to try and use the data access classes with the Telerik RadGrid which I can bind using the OpenDataSource object, but it says I need to close the connection object and use the datareader.close() command.  I want to be sure I don't leave anything open which might use up memory, etc...What should I modify so that the openDataSource object can be used?
Thanks

For example it does this:
SQLDataReader sdrRole = null;
try
{
sdrRole = dbRole.GetRoleDetail(param1, param2, etc)
}
finally
{
if (sdrRole != null)
{
if (!sdrRole.IsClosed)
sdrRole.Close();
sdrRole = null;
}
}

Code in the class file:
       public SqlDataReader GetRoleDetail(int byUserID, int roleID)
        {
            SqlCommand cmd = new SqlCommand();

            try
            {
                // Set command statement
                cmd.CommandText = "spSelectRoleDetail";
                cmd.CommandType = CommandType.StoredProcedure;

                // Add parameters
                cmd.Parameters.Add(_db.MakeParam("@by_user_id", SqlDbType.Int, ParameterDirection.Input, 0, byUserID));
                cmd.Parameters.Add(_db.MakeParam("@role_id", SqlDbType.Int, ParameterDirection.Input, 0, roleID));

                // Execute procedure
                return _db.OpenSqlDataReader(cmd);
            }

            finally
            {
                cmd.Dispose();
                cmd = null;
            }
        }

        //============================================================================    
        /// <summary>
        /// Executes the passed SqlCommand object and returns a SqlDataReader object
        /// </summary>
        /// <param name="cmd">SqlCommand object to be executed</param>
        /// <returns>SqlDataReader object</returns>
        //============================================================================    
        public SqlDataReader OpenSqlDataReader(SqlCommand cmd)
        {
            try
            {
                // Check for incoming connection
                if (cmd.Connection == null)
                {
                    // Open default connection
                    base.Open();
                    cmd.Connection = base.Connection;
                }

                // Execute command
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }

            catch (System.Data.SqlClient.SqlException exp)
            {
                throw BuildException(exp);
            }
        }

        //==============================================================================
        /// <summary>
        /// Open the connection.
        /// </summary>
        //==============================================================================
        public void Open()
        {
            // open connection
            if (_conn == null)
            {
                _conn = new SqlConnection(_connString);
                _conn.Open();
            }
            else
            {
                if (_conn.State != ConnectionState.Open)
                    _conn.Open();
            }
        }

        //==================================================================================
        /// <summary>
        /// Dispose of the database...
        /// </summary>
        //==================================================================================
        public void Dispose()
        {
            if (_db != null)
            {
                _db.Dispose();
                _db = null;
            }
        }

0
Comment
Question by:cenetadmin
  • 4
  • 2
7 Comments
 
LVL 21

Expert Comment

by:silemone
ID: 22799641
you can close it immediately if you add it to a session variable...

but ideally, you don't need to close your DataReader...you need to close your connection to your Database, but not your datareader...it may cause errors.  Once I tried to dispose of my DataTable at the end of a table after i had finished using it in a finally block and the program gave me major problems on the next go around.
0
 

Author Comment

by:cenetadmin
ID: 22799652
to be more specfic, what code should I comment out, or modify in the code I included?
0
 
LVL 21

Expert Comment

by:silemone
ID: 22799672
oops excuse my earlier comments.  

close it as soon as you've retrieved all data and placed into a table or list.
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
LVL 21

Expert Comment

by:silemone
ID: 22799713
wow, you've broken your code so far apart...i would suggest debugging...placing a break point to find out when a connection is already opened and not closed before another connection starts...
0
 

Author Comment

by:cenetadmin
ID: 22799745
will not be able to try this until Monday.  Sorry for the delay.
0
 
LVL 21

Accepted Solution

by:
silemone earned 500 total points
ID: 22799799
no problem...enjoy your weekend
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22803935
i will not recommend you to use the kind of design you are going to use and asking the question regarding it.

in my view point instead of returning the data reader object back you should extract the information from it, add it into an objet which can hold that information and then return back that object so that your data reader will be created, used and disposed within the same functions scope so that the garbage collection can be done better instead of the references floating around
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Visual Studio npm 1 29
SSRS 2013 - Finding Datasets/StoredProcedures 4 32
Need to merge 3 large tables into one Table in SQL server 2 19
Record locking on classic ASP 3 37
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question