Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 434
remdao Avatar asked Nov 03 '25 19:11

remdao


1 Answers

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.

like image 139
Frederik Gheysels Avatar answered Nov 05 '25 10:11

Frederik Gheysels