Click here to Skip to main content
15,914,417 members
Home / Discussions / .NET (Core and Framework)
   

.NET (Core and Framework)

 
GeneralRe: Database connection Pin
dojohansen15-Apr-09 3:36
dojohansen15-Apr-09 3:36 
GeneralRe: Database connection Pin
Pete O'Hanlon15-Apr-09 1:54
mvePete O'Hanlon15-Apr-09 1:54 
GeneralRe: Database connection Pin
dojohansen15-Apr-09 2:40
dojohansen15-Apr-09 2:40 
GeneralRe: Database connection Pin
Pete O'Hanlon15-Apr-09 4:38
mvePete O'Hanlon15-Apr-09 4:38 
AnswerRe: Database connection Pin
Colin Angus Mackay11-Apr-09 6:24
Colin Angus Mackay11-Apr-09 6:24 
AnswerRe: Database connection Pin
Fernando Soto11-Apr-09 8:09
Fernando Soto11-Apr-09 8:09 
AnswerRe: Database connection Pin
PIEBALDconsult13-Apr-09 4:16
mvePIEBALDconsult13-Apr-09 4:16 
AnswerRe: Database connection Pin
dojohansen14-Apr-09 22:02
dojohansen14-Apr-09 22:02 
Hi,

the answer is that in ADO.NET you should always close the connection when it isn't in use. The connection classes manage the underlying TCP connection for you, so although you are "logically" closing the connection you are not in fact incurring the cost of tearing down and reestablishing the database connection each time.

In practice this makes the most difference in server apps where connection pooling is of great use. Whenever your code closes a connection it in fact simply releases that connection to the pool, and the next time an instance of a connection is constructed that uses the exact same connection string the pre-existing connection is returned. (There is something involved to make the connection state as if it was a freshly established one - see 'sp_reset' in SQL Server, not sure exactly how this is implemented with the other providers.)

But even in a desktop app where each client has a dedicated connection to the database and no pooling takes place it's considered good practice to open and close the connection. I think it is; it makes error handling a little easier. You still have to catch exceptions and perhaps log and present errors, but if the user wishes to retry an operation there's no additional logic to check the state of the connection or find out if it's necessary to open it first, because you simply *always* open it where you need it and close it when you're done with it.

I personally use a simple connection wrapper class to centralize the code implementing the patterns I wish to use. You may not bother doing this if you use code generation for most of your data access code, but if you hand-code this stuff it makes a huge difference - much less code, far fewer errors, and much easier debugging. And if you just put this class in a separate library and never put anything app-specific in it you'll start building reusable code that has applications everywhere.

For example, with my Connection class you can do very common tasks like these very easily:
  // Get a connection from configuration. Why rewrite the same code all over the place?
  Connection c = Connection.FromConfig("mainDB");
  
  // Similar with the open-and-close logic. Why not centralize it so it's transparent?
  int count = c.ExecuteScalar<int>("select count(*) from [table] where [col] < @p0", value);

  // SqlTransaction is a mess; it doesn't support nesting, and you must write code to associate each
  // SqlCommand with the transaction object before executing it. Why not automate this tedious code
  // that is just plumbing and isn't oriented towards the functionality of your app?
  using (c.BeginTransaction())
  {
    c.ExecuteProc("update_stock");
    c.ExecuteNonQuery("truncate table [pending_orders]");
    someOtherObject.DoSomething(c);
    c.CommitTransaction();
  }
  string[] popular = c.GetColumn<string>("select top 10 p.name from product p join sales s on s.productID = p.id order by s.itemsSold desc");
</string></int>


These are just a few examples. The feature shown with the generic ExecuteScalar<t> method is used basically everywhere strings are used to specify command texts. It's inspired by the string formatting feature, as in string.Format("{0} loves {1}", "Dag", "Jennifer"). Just like here "{0}" refers to the first argument in the args array, we adopted the naming convention "@p<index>" so that the first argument is the value for a parameter named "@p0", the second one named "@p1" and so on. It's simple, efficient, and encourages use of parameterized queries where lazy programmers might otherwise simply concatenate strings (which of course is very dangerous since it opens the door to SQL injection attacks).

I really think I should prepare a CodeProject article to present this logic. It's quite simple but I feel a lot of people might find it useful.
GeneralRe: Database connection Pin
Colin Angus Mackay15-Apr-09 2:37
Colin Angus Mackay15-Apr-09 2:37 
GeneralRe: Database connection Pin
dojohansen15-Apr-09 2:59
dojohansen15-Apr-09 2:59 
GeneralRe: Database connection Pin
Paulo Zemek29-Apr-09 11:48
Paulo Zemek29-Apr-09 11:48 
AnswerRe: Database connection Pin
saanj29-Apr-09 0:01
saanj29-Apr-09 0:01 
GeneralRe: Database connection Pin
EmZan29-Apr-09 0:06
EmZan29-Apr-09 0:06 
Questionsecurity problem in asp.net Pin
deepak baldia9-Apr-09 19:15
deepak baldia9-Apr-09 19:15 
AnswerRe: security problem in asp.net Pin
Colin Angus Mackay10-Apr-09 2:48
Colin Angus Mackay10-Apr-09 2:48 
Questionhello Pin
mohamedmrc9-Apr-09 10:02
mohamedmrc9-Apr-09 10:02 
AnswerRe: hello Pin
Eddy Vluggen9-Apr-09 10:47
professionalEddy Vluggen9-Apr-09 10:47 
AnswerRe: hello Pin
led mike9-Apr-09 10:56
led mike9-Apr-09 10:56 
GeneralRe: hello Pin
Pete O'Hanlon12-Apr-09 11:03
mvePete O'Hanlon12-Apr-09 11:03 
QuestionSafe thread termination in unmanaged code Pin
supercat99-Apr-09 8:06
supercat99-Apr-09 8:06 
AnswerRe: Safe thread termination in unmanaged code Pin
led mike9-Apr-09 9:10
led mike9-Apr-09 9:10 
GeneralRe: Safe thread termination in unmanaged code Pin
supercat99-Apr-09 9:44
supercat99-Apr-09 9:44 
GeneralRe: Safe thread termination in unmanaged code Pin
led mike9-Apr-09 10:55
led mike9-Apr-09 10:55 
GeneralRe: Safe thread termination in unmanaged code Pin
supercat99-Apr-09 11:43
supercat99-Apr-09 11:43 
GeneralRe: Safe thread termination in unmanaged code Pin
Luc 64801110-Apr-09 2:57
Luc 64801110-Apr-09 2:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.