简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM