Skip to content
Advertisement

C# sql create one connection and open and close for each query

I recently inherited a C# Web app that creates a new connection for every query like so:

I understand that this is typically the best way to do it, but is it acceptable or “best practice” to have the constructor create the connection object, and then have each method/Query open and then close that connection like so:

I prefer the second way as it does not make multiple connection objects. However, the first way would also be preferable if I were to make the methods and class static.

Advertisement

Answer

Either one of these are acceptable. A SqlConnection uses a connection-pool so it shouldn’t affect performance much. Having multiple SqlConnection objects isn’t going to hurt anything. This comes down to a preference.

I would suggest encapsulating the commands in a using statement if you keep the connections inside the methods, such as:

This ensures proper disposal of the connection.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement