C # .NET using block

I want to use the "using" block in my DAL layer. how

using (SqlConnection con = new SqlConnection("connection string"))
{
     Command object
     Reader object
}

Since the SqlConnection object initialized in the use block, I know that this connection object will be automatically deleted when the control leaves the scope of the block.

But I am creating Command and Reader objects inside the use block. Should I explicitly close them or do I need to write another “used” block for them.

+3
source share
5 answers

You should also use them usingfor commands and reading or explicitly close them.

I usually code it like this:

var sql = "SELECT * FROM table";
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, cn)) {
}

This limits the number of identifiers.

+4
source

- , ..

using (SqlConnection con = new SqlConnection("connection string"))
{
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = "select * from table";
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            ...
        }
    }
}
+3

, IDisposable. , , , .

+2

using , IDispose. , using , .

+1

You should use blocks using()or finallyif you do not like to use your connections and readers. For readers, the connection does not close until the reader closes. In addition, I read that it using()does not guarantee 100% that the connection will be closed, but I do not know the reason for this, since it is converted to try-finally and will be executed in any state.

0
source

Source: https://habr.com/ru/post/1781194/


All Articles