Handle database connections with care

Rate It (1)

Last post 03-22-2009 4:47 PM by yorock. 36 replies.

Sort Posts:

  • Handle database connections with care

    12-19-2004, 11:22 AM
    Locked
    • Star
      8,255 point Star
    • bdesmet
    • Member since 08-04-2002, 6:39 AM
    • Belgium
    • Posts 1,651
    Please make sure that you always close the underlying connection to a database and that you're using connection pooling to improve the processing speed of database connection creation etc. A few tips:

    1. Use web.config to store the connection string:
    <configuration>
    
    <appSettings>
    <add key="dsn" value="server=server; uid=user; pwd=password; database=db" />
    </appSettings>
    </configuration>

    2. Always use this connection string and don't make modifications to it. If you're not doing this (i.e. using different DSNs) you'll disable the connection pooling feature:
    string dsn = System.Configuration.ConfigurationSettings.AppSettings["dsn"];

    3. Don't apply tricks to try to manage connections etc, just go ahead and use it (no wrapper classes or so involved):
    SqlConnection conn = new SqlConnection(dsn);

    4. Make the time between conn.Open() and conn.Close() as short as possible. E.g. don't do this:
    SqlConnection conn = new SqlConnection(dsn);
    
    conn.Open();
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.Parameters.Add(...);
    //and more cmd parameters actions etc
    SqlDataReader reader = cmd.ExecuteReader();
    //use the reader and do a lot of other work, not relying on the database
    conn.Close();

    but rather, use:
    SqlConnection conn = new SqlConnection(dsn);
    
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.Parameters.Add(...);
    //and more cmd parameters actions etc
    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();
    //use the reader
    conn.Close();
    //do a lot of other work, not relying on the database

    5. Always close the connection when you're done, even when an exception occurs. To do this, use the try...finally pattern:
    SqlConnection conn = new SqlConnection(dsn);
    
    try
    {
    //some init depending on conn
    conn.Open();
    //minimum number of lines of code depending on the open connection
    }
    finally
    {
    if (conn.ConnectionState == ConnectionState.Open)
    conn.Close();
    }

    or the using pattern in C#:
    using (SqlConnection conn = new SqlConnection(dsn))
    
    {
    //...
    conn.Open();
    }

    which will close the db connection automatically when leaving the using block.
    Bart De Smet [MVP]



    Visit www.msdn.be, www.bartdesmet.net
  • Re: Handle database connections with care

    01-24-2008, 3:10 AM
    Locked
    • Member
      199 point Member
    • sam_soumya
    • Member since 01-10-2008, 11:42 AM
    • Posts 94

     Hello sir,

                    It is a nice post .May you please help me for my following database related requirement .

    Let there are two field   1. id--->auto increment or 1 increment serially.

                                      2.name-->varchar

           the requirement is  : if i delete a record ,it will  be  rearrenged.  Like there are 5 records from id 1...to 5.If i delete the 3rd one then the id's will be

    rearrenged again from 1...to 4 . So,what should i do in this case.

     

    Thanks. 

                 
     


     

    Thanks & Regards.
    Soumya
  • Re: Handle database connections with care

    01-24-2008, 5:29 PM
    Locked
    • Member
      446 point Member
    • sayyazahmad
    • Member since 01-17-2008, 11:46 PM
    • US
    • Posts 90
    If you are using SQL Server 2005, you can use Row_Number() instead while retrieving the data.Try this query: Select EmployeeID, EmployeeName,          Row_Number()          Over ( Order by EmployeeID, EmployeeName ) As RowNumber

    From Employees

    Please Mark As Answer if it helps you!
  • Re: Handle database connections with care

    01-24-2008, 11:31 PM
    Locked
    • Member
      199 point Member
    • sam_soumya
    • Member since 01-10-2008, 11:42 AM
    • Posts 94

     Thank you very much Sir for your Reply.It is working fine..

    Thanks & Regards.
    Soumya
  • Re: Handle database connections with care

    02-11-2008, 7:02 PM
    Locked
    • Member
      79 point Member
    • deddy_one
    • Member since 11-01-2007, 10:03 AM
    • Posts 65

    The using pattern in C# is new for me.

    thanks for sharing this

  • Re: Handle database connections with care

    02-17-2008, 2:50 AM
    Locked
    • Member
      25 point Member
    • SirPaladin1969
    • Member since 02-14-2008, 10:48 PM
    • Albany, NY
    • Posts 58

    I'm not entirely understanding point #1. Whose UserName and Passwords would be hard coded in the web.config? Wouldn't each user need to login with their own UserName and Password to gain access? Do you add Keys for each? That would seem very inefficient if you had lots of users.

  • Re: Handle database connections with care

    03-05-2008, 2:16 PM
    Locked
    • Contributor
      2,217 point Contributor
    • sudipta
    • Member since 02-25-2008, 3:33 PM
    • India
    • Posts 455

    Hi bdesmet,

    Nice post. Everybody should always take out some time to make such valuable posts.

    Please click "Mark As Answer" if this hepled in solving your problem.
  • Re: Handle database connections with care

    04-22-2008, 1:07 AM
    Locked
    • Member
      6 point Member
    • ManishKadu
    • Member since 04-22-2008, 5:04 AM
    • Posts 3

    Nice post

    Filed under:
  • Re: Handle database connections with care

    05-14-2008, 4:22 PM
    Locked
    • Member
      160 point Member
    • imbrod
    • Member since 10-27-2004, 8:43 AM
    • Posts 221

    " 4. Make the time between conn.Open() and conn.Close() as short as possible."

    This is probably the most quoted ADO and ADO.NET-related statement of all times... But nobody ever explains this (I had the same wonders back in ASP):

    If I have to make 3 times building commands and executing readers, do I:

    a) open cn - cm1,reader1 - close cn  ; open cn - cm2,reader2 - close cn  ; open cn - cm3,reader3 - close cn  ;

    or

    b) open cn - cm1, reader1, cm2, reader2, cm3, reader3 - close cn 

    I love spaghetti (both code and food)!
  • Re: Handle database connections with care

    05-14-2008, 11:46 PM
    Locked
    • All-Star
      98,827 point All-Star
    • mbanavige
    • Member since 11-06-2003, 1:29 PM
    • New England, USA
    • Posts 10,419
    • Moderator
      TrustedFriends-MVPs

    create all you obects before opening the connection

    create connection

    create command

    etc...

    whatever does not need access to that open connection should be done before you open it or after you close it.

    then

    1. open connection
    2. executereader
    3. process reader
    4. closeconnection

     

    Mike Banavige
    ~~~~~~~~~~~~
    Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/
  • Re: Handle database connections with care

    05-15-2008, 6:32 AM
    Locked
    • Member
      160 point Member
    • imbrod
    • Member since 10-27-2004, 8:43 AM
    • Posts 221

    mbanavige:


    1. open connection
    2. executereader
    3. process reader
    4. closeconnection

     

     

    So you're saying:

     

    1. open connection
    2. executereader1
    3. process reader1
    4. executereader2
    5. process reader2
    6. executereader3
    7. process reader3
    8. closeconnection

     

    OR

     

    1. open connection
    2. executereader1
    3. process reader1
    4. close connection
    5. open connection
    6. executereader2
    7. process reader2
    8. close connection
    9. open connection
    10. executereader3
    11. process reader3
    12. closeconnection

     

    I love spaghetti (both code and food)!
  • Re: Handle database connections with care

    05-15-2008, 4:45 PM
    Locked
    • Member
      60 point Member
    • jaimalchohan
    • Member since 01-12-2005, 5:52 AM
    • Posts 23

      For the above you have 2 clean solutions. 

    Solution 1: IDataReader.NextResult()

    If you have mutiple select statements in your Sql stored procedure, you can move onto a different result set by using the NextResult() method of the DataReader.  This means you only have 1 DBConnection.Open() and as all the data is returned in 1 go, there is actually less overhead in retriving the results

    Solution 2: XmlReader()

    By using the  DBCommand.ExecuteXmlReader() method you can retirve XML data from your Sql stored procedure, this does mean that you need to format your stored procedure output as valid XML (which is as easy as Linq in T-SQL using the FOR XML PATH feature)  You can then retrive a sligtly verbose but very easy to manipulate XML Fragment or Document which you can load into an XmlDocument.  My current preference is to use this method, espcieally in .NET 3.5 as Linq-To-XML makes the content very easy to manipulate.

  • Re: Handle database connections with care

    05-15-2008, 5:18 PM
    Locked

    I think one of the best practise to work with a data reader would be to use the COMMAND BEHAVIOUR enum's CloseConnection member.

     

    It is used like :
    IDataReader = cmd.ExecuteReader(CommandBehaviour.CloseConnection);

    This way the connection is always closed when the data reader is closed. 

     

    Ashutosh Bhardwaj
  • Re: Handle database connections with care

    05-16-2008, 5:41 AM
    Locked
    • Member
      160 point Member
    • imbrod
    • Member since 10-27-2004, 8:43 AM
    • Posts 221

    So you're saying, I should close connection immediately (although soon I'll have to open it again?) Is that an answer?

    My question is this: (It's the same question for last 9 years, from the days of ADO and ASP, but I've never got straight answer): 

    a) Should I open and close connection several times if I need it several times on the page (let's say several datareaders that will bound to several Repeaters)

    b) Should I open and close connection once (but this way the connection will stay opened longer until several datareaders are processed and bound to repeaters)

    What's the better solution? 

    I love spaghetti (both code and food)!
  • Re: Handle database connections with care

    05-16-2008, 5:52 PM
    Locked
    • Member
      60 point Member
    • jaimalchohan
    • Member since 01-12-2005, 5:52 AM
    • Posts 23

    It depends on your applications specific requirements.. 

    Opening and closes connections causes overhead.

    Keeping a connection open for longer could cause delays for other users, in a high traffic website that is. 

    If you're reading a lot of data from a particular table then that could cause a lock on the table (unless you read with a nolock)

    There's no right or wrong.I have never coded in such a way that I've had to hold a conection open for multiple DBCommands, I dislike it.  However if I had no other choice then I would implement a solution and monitor performace using Sql Profiler. 

Page 1 of 3 (37 items) 1 2 3 Next >