Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I open and close a connection to SQL Server

I have a simple static class with a few methods in it. Each of those methods open a SqlConnection, query the database and close the connection. This way, I am sure that I always close the connection to the database, but on the other hand, I don't like to always open and close connection. Below is an example of what my methods look like.

public static void AddSomething(string something) {     using (SqlConnection connection = new SqlConnection("..."))     {         connection.Open();         // ...         connection.Close();     } } 

Considering that the methods are inside a static class, should I have a static member containing a single SqlConnection? How and when should I drop it? What are the best practices?

like image 384
Martin Avatar asked May 14 '09 04:05

Martin


People also ask

Should you keep SQL connection open?

From MSDN, "Note If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose." Cheers!

Why is it important to close a connection to a database?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.

Should I close connection after each query?

Open the connections just when you need to execute a query and close it as early as possible. So my solution is, YES. Show activity on this post. if your application doesn't close connection properly may lead to some issues like the connection pool maxing out.


1 Answers

No, don't keep a static SqlConnection unless you have to. Threading would be one concern, but more importantly - usually you simply don't need to. With your code as presented, the internal connection pooling means that most of the time you will get the same underlying connection on successive calls anyway (as long as you use the same connection string). Let the pooler do its job; leave the code alone.

This also avoids the issues of what happens when you start having two threads... now each can do work on their own connection; with static (assuming you don't use [ThreadStatic]) you'd have to synchronize, introducing delays. Not to mention re-entrancy (i.e. a single thread trying to use the same connection twice at the same time). Yup; leave the code alone. It is fine now, and almost any change you make would make it not fine.

like image 60
Marc Gravell Avatar answered Oct 03 '22 17:10

Marc Gravell