A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of DatabaseRecord
. There are a number of methods like Load()
, Save()
etc. In my initial implementation I created a connection to the DB in the constructor of DatabaseRecord
e.g.
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
I then call Open()
and Close()
on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class.
I've just been doing some reading though and it appears that this pattern is recommended in a number of places:
using (var connection = new SqlConnection(...)) {
connection.Open();
// Stuff with the connection
connection.Close();
}
I can see why it's desirable - the connection is automatically Dispose()
d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling new SqlConnection()
potentially many times like this.
Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.
Creating a SqlConnection Object A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and instantiate the SqlConnection all at the same time, as shown below: SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.
SQLServerConnection is not thread-safe, however multiple statements created from a single connection can be processing simultaneously in concurrent threads.
To set the maximum pool size: n is the number of connections allowed per pool, from 1 to 2,147,483,647 (the default).
Yes, it is best practice. The using
makes your call to Close() exception-safe.
And the overhead of creating a (any) object is indeed minimal, and smallest for short-lived objects (that stay in GC generation 0).
Note that you don't have to call Close() at the end of the using-block anymore, it is automatically done for you (Dispose==Close).
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