SqlDataAdapter SqlCommand or call the Dispose method, will close the SqlConnection bound? (Reprint)

1. Does SqlCommand.Dispose close the connection?

ask


 

Can I use this approach efficiently?

using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
    cmd.Connection.Open();
    // set up parameters and CommandType to StoredProcedure etc. etc.
    cmd.ExecuteNonQuery();
}

My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?

 

answer


 

No, Disposing of the SqlCommand will not effect the Connection. A better approach would be to also wrap the SqlConnection in a using block as well:

using (SqlConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
    {
        cmd.ExecuteNonQuery();
    }
}

Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should be disposed of as well, and likely more important to dispose of than a command.

 

EDIT:

I just tested this:

SqlConnection conn = new SqlConnection(connstring);
conn.Open();

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

conn.Dispose();  

The first command was disposed when the using block was exited. The connection was still open and good for the second command.


So, disposing of the command definitely does not dispose of the connection it was using.

 

Description link

 

 

2. Does SqlDataAdapter.Dispose actually Close an associated SqlConnection?

ask


 

Does anyone know if the SqlDataAdapter.Dispose method actually closes or disposes any SqlConnections? I loaded up Reflector and I see that SqlDataAdapter inherits from DbDataAdapter. If I disassemble and look at the dispose method in that class, there appears to be no disposal of any SqlConnections. I suppose I could write a test for this, but I figured I would ask to see if anyone had any insight on this.

 

answer


 

The first thing to be aware of is that the DataAdapter does manage and close your connection in some circumstances. For example, if you're using a DataAdapter you're probably operating on DataTables/DataSets using the .Fill() and .Update() functions.

From the .Fill() docs:

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

The .Update() docs don't mention anything about the connection at all, so I would expect to need to manage it manually.

Now you asked specifically about the Dispose() method. Like Update, the Dispose() docs don't specifically mention the connection, so I would expect to need to close it manually.

Finally, we can improve on Bob King's code slightly like this:

Using conn as New SqlConnection(""), _
      adapter as New SqlDataAdapter() With {.Connection = conn}
    'Do stuff
End Using

Or in C#:

using (SqlConnection conn = new SqlConnection(""))
using (SqlDataAdapter adapter = new SqlDataAdapter() {Connection = conn})
{
    // Do stuff
}

Not 100% I got the initialize syntax for the adapter right, but I typed it directly into the reply window. I'll fix it later if needed.

 

Description link

 

 

3. Does SqlDataAdapter close the SqlConnection after Fill() function?

ask


 

Does SqlDataAdapter close the SqlConnection after the Fill() function or do I need close it myself?

string cnStr = @"Data Source=TEST;Initial Catalog=Suite;Persist Security Info=True;User ID=app;Password=Immmmmm";
cn = new SqlConnection(cnStr);
SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Date", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
adapter.Fill(ds);

cn.Close() // ????????

Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(cn.State);

 

answer


 

In your current usage, it will close for you:

If the IDbConnection is closed before Fill is called, it is opened to retrieve data and then closed. If the connection is open before Fill is called, it remains open.

DbDataAdapter.Fill Method

I think it's always better to explicitly cater for it yourself with a using statement:

using (SqlConnection conn = new SqlConnection(""))
{
    conn.Open();

    // Do Stuff.

} // Closes here on dispose.

This is often more readable and doesn't rely on people understanding the inner workings of SqlDataAdapter.Fill, just the using statement and connections.

However, if you know the connection is closed before the adapter uses it (as in, you've just created the connection) and it's not used for anything else, your code is perfectly safe and valid.

Personally, I'd write something like this:

string cnStr = "Data Source=TEST;Initial Catalog=Suite;Persist Security Info=True;User ID=app;Password=Immmmmm";
DataSet ds = new DataSet();

using (SqlConnection cn = new SqlConnection(cnStr))
{
    using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Date", cn))
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            cn.Open();
            adapter.Fill(ds);
        }
    }
}

 

Description link

 

Guess you like

Origin www.cnblogs.com/OpenCoder/p/12067826.html