views:

263

answers:

3

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?

+2  A: 

Usually you should create a new connection for each command and take advantage of the in-built connection pooling.

M4N
This is definetly a bad practice ...
Frederik Gheysels
I assume each client will execute one command at a time. So I don't see what is bad practice
M4N
+4  A: 

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.

Mark Seemann
+4  A: 

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.

Frederik Gheysels