Overhead of creating a new SqlConnection in C #

A back, I wrote an ORM layer for my .net application, where all database rows are represented by a subclass DatabaseRecord. There are several methods, such as Load(), Save()etc. In my initial implementation, I created a database connection in the constructor DatabaseRecordfor example.

connection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);

Then I call Open()and Close()this SqlConnection at the beginning and end of my methods that access the database. It seemed to me (as someone who was familiar with programming, but new to C # and .net), to be the most effective way to do something - to have one connection and open / close it where necessary inside the class.

I just read a little and it seems that this pattern is recommended in several places:

using (var connection = new SqlConnection(...)) {
    connection.Open();
    // Stuff with the connection
    connection.Close();
}

, - Dispose() d, , , . , new SqlConnection() , .

, , , , , .

+5
3

, . using Close().

() ( GC 0).

, Close() , (Dispose == Close).

+8

. , , ( ) , .

, , , .

, , Dispose . Close, Dispose. using dispose, , Close.

+1

If you are not sure about the cost of opening / closing a connection, enter a SqlConnectionmember variable of your class, but create a class IDisposableand remove SqlConnection when the class is located

+1
source

All Articles