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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With