Share via

How to connect SQL server once

BenTam 1,806 Reputation points
2021-10-02T05:03:11.307+00:00

Since connecting to SQL server takes time, I want to open once an the connection handle. The connection handle is to be used in any position of a solution. Could anyone tell me how to do it?

TIA

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

P a u l 10,766 Reputation points
2021-10-02T05:39:19.267+00:00

In practice there's not much point trying to optimise SQL connections (unless you have measured the performance issues of your application and a new strategy becomes necessary), as connections are already heavily optimised by ADO.NET using connection pooling, meaning that if you instantiate a SqlConnection and call .Open() on it, this isn't to say that you're opening a new connection. It may be an already opened connection that's no longer in use that can be repurposed for your new connection.

Before considering this approach it's worth having a read of this article:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling

Particularly the first paragraph which summarises what pooling is, as well as this word of caution:

   We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside a using statement in C#, or a Using statement in Visual Basic. Connections that are not explicitly closed might not be added or returned to the pool.  

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.