简体   繁体   中英

A new sql connection for each query?

I'm writing a server application that's communication with a local sql server.

Each client will need to read or write data to the database.

Would it be better to have a thread safe class which will enqueue and executes the sql commands on a single sql connection? Or should I open a new connection for each command? Does it matter much for performance?

If you are using any flavor of ADO.NET, connection pooling will automatically be used (at least with SQL Server) unless you explicitly disable it, so there's no reason to do anything special about that.

Be sure to remember to Close your connections after each used - this will simply return the connection to the connection pool.

If you have a batch of statements that have to be executed after each other, you should use the same SqlConnection. As soon as you do not longer need the SqlConnection, and you do not know when you will need a connection again, you should close the connection.

So, if you have to execute 2 insert statements and one update statement after each other, for instance, you should use the same SqlConnection.
The most important advantage here, is that you can put those statement in a transaction if necessary. Transactions cannot be shared accross connections.

When you're finished working with the DB, you can close the connection. By default, connection pooling is used, and the connection will be returned to the pool, so that it can be reused the next time you need a connection to the DB. Connection lifetime should be short, but you should not use a separate connection for each DbCommand.

通常,您应该为每个命令创建一个新连接,并利用内置连接池。

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