Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to creating a new SQL connection for each query?

Tags:

c#

sql

sql-server

I am trying to design an efficient application that connects to a SQL Database and I was wondering what the merits/demerits of creating a SQL connection for each SQL query is, Eg, Like the code below, making a class with the connection set once so you can call on it when ever you need it in the class.

class SqlQuery
    {
        SqlConnection Connection = new SqlConnection(@myConnectionString);
          public void fillInfoData()
          {
              SqlCommand updateCommand = new SqlCommand(
                    @"my sql query", Connection);
              Connection.Open();
              updateCommand.ExecuteNonQuery();
              Connection.Close();
          }
    }

Or should you create a new connection for each new query?

  • EDIT: Jon Skeet recommended creating a new connection for each query, I was wondering why?
  • EDIT No 2: He stated it in this answer.
like image 225
KyloRen Avatar asked Nov 01 '25 20:11

KyloRen


2 Answers

You open a connection per query and then when you close it, it goes back to the connection pool and the framework will manage the rest

So you do not have to worry about keeping connection alive, timeouts etc...

MSDN Article

https://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx

like image 104
Hassan Avatar answered Nov 03 '25 10:11

Hassan


I think what he meant was not to keep a global connection object that is open. But you need to create an SqlConnection when you need it, execute all the queries needed at the point (Not a single connection per each query) and then close the connection.

So if you have a bunch of queries that needs to be executed, you don't need a single sql connection for each but one is only enough. But if you're executing a query each time the user clicks a button for example, it's better to open a connection on each click, because that way it is easier to manage closing and disposing the connection.

like image 22
Zein Makki Avatar answered Nov 03 '25 09:11

Zein Makki