CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Apr 2007
    Posts
    32

    Keep Alive SQL Server

    Hello All,

    I would like to ask you how can I keep alive SQL connection?

    Thanks in advance.

  2. #2
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    Re: Keep Alive SQL Server

    why would you want to keep a sql connection alive?

  3. #3
    Join Date
    Apr 2007
    Posts
    32

    Re: Keep Alive SQL Server

    Just for checking connection if something happened with server try to reconnect.

  4. #4
    Join Date
    Jul 2006
    Posts
    297

    Re: Keep Alive SQL Server

    Sql connections you want to close as soon as you're done. You should try you best to never keep an SQL Connection open. They're a limited resource the server can only handle so many.

  5. #5
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Keep Alive SQL Server

    I am not sure what you are actually asking. But in case you want to check whether the connection is alive, you can use SqlConnection.State property to determine whether the connection is still active or handle SqlConnection.StateChange event to determine when the connection changes the state.

    As already stated in post # 2, why would want to keep a connection active all the time? You should just open the connection and close it once the process is completed.

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Keep Alive SQL Server

    Most modern db providers (like SqlConnection) internally cache connections.

    So you wrap the connection in a using block, but open a connection every time that you need to hit the database.

    It sounds expensive, but it really isn't because most providers hold onto a pool of connections and they keep a hold on them for a given time period.

    Sure the provider will release the connections after a period of inactivity, but how reliable would a connection be if you kept a connection opened for several hours (or days)?

    Chances are, you're just going to have to check that the connection is valid, find it isn't and reconnect anyway.

    Try creating a connection every time and let the provider do it's pooling job.

    Code:
     
    using( SqlConnection cn = new SqlConnection( ... ) )
    {
      // do db work here
    }

  7. #7
    Join Date
    Apr 2007
    Posts
    32

    Re: Keep Alive SQL Server

    Thank you for your replies ) I'll try all ideas.
    Thanks again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured