There's a lot of non-detailed questions on this one, so here goes.
What is the best practice for connection handling in C# with SQL Server 2008? We have an assembly (which in our case is used by a WCF Service) that makes calls to an SQL Server. In general it seems like you need three objects to do this: The connection object, the command object, and the reader object.
The only reliable way we've been able to get the calls to work is to do the following:
- Open the connection.
- Create the Command in a using() { } block
- Create the Reader to handle the response.
- Dispose of the reader.
- Implicitly dispose of the Command at the end of the using() block
- Close the connection.
We ran into an unusual problem when running the same command multiple times iteratively, where it would complain that there was already a command or reader object attached to the connection that was still open. The only rock solid solution was to close and reopen the connection with every command we did, iterative or just sequential (different commands.)
So this is the question, since I come from a mysql_pconnect background on DB connection handling.
- Is it going to significantly impact performance to be opening and closing a connection for each command?
- If so for 1., what is the proper workaround, or code structure to handle serially repeating a command?
- Is there any way to reuse a connection, command or reader at all?
- If not for 3., does this really impact performance or memory usage significantly (As in, our users would notice.)