1. Does SqlCommand.Dispose close the connection?


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?


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.

原文链接

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


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.


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.

原文链接

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


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[].Rows.Count);
Console.WriteLine(cn.State);


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);
}
}
}

原文链接

调用SqlCommand或SqlDataAdapter的Dispose方法,是否会关闭绑定的SqlConnection?(转载)的更多相关文章

  1. 强制回收和IDisposable.Dispose方法

    如果某对象的 Dispose 方法被调用一次以上,则该对象必须忽略第一次调用后的所有调用. 如果对象的 Dispose 方法被多次调用,该对象一定不要引发异常. 除Dispose 之外的实例方法在资源 ...

  2. 编写高质量代码改善C#程序的157个建议——建议48:Dispose方法应允许被多次调用

    建议48:Dispose方法应允许被多次调用 一个类型的Dispose方法应该允许被多次调用而不抛出异常.鉴于此,类型内部维护了一个私有的bool变量disposed,如下: private bool ...

  3. SqlCommand和SqlDataAdapter的区别

    SqlDataAdapter对象 一.特点介绍1.表示用于填充 DataSet 和更新 SQL Server 数据库的一组数据命令和一个数据库连接.2.在SqlDataAdapter和DataSet之 ...

  4. C# SqlCommand和SqlDataAdapter的区别

    SqlCommand和SqlDataAdapter的区别 SqlCommand对应DateReader   SqlDataAdapter对应DataSet   SqlCommand的执行效率比较高,但 ...

  5. JS魔法堂:定义页面的Dispose方法——[before]unload事件启示录

    前言  最近实施的同事报障,说用户审批流程后直接关闭浏览器,操作十余次后系统就报用户会话数超过上限,咨询4A同事后得知登陆后需要显式调用登出API才能清理4A端,否则必然会超出会话上限.  即使在页面 ...

  6. 实现 Dispose 方法

    实现 Dispose 方法 MSDN 类型的 Dispose 方法应释放它拥有的所有资源.它还应该通过调用其父类型的 Dispose 方法释放其基类型拥有的所有资源.该父类型的 Dispose 方法应 ...

  7. 定义页面的Dispose方法:[before]unload事件启示录

    前言 最近实施的同事报障,说用户审批流程后直接关闭浏览器,操作十余次后系统就报用户会话数超过上限,咨询4A同事后得知登陆后需要显式调用登出API才能清理4A端,否则必然会超出会话上限. 即使在页面上增 ...

  8. 是否需要手动执行DataContext的Dispose方法?

    我们知道DataContext实现了IDisposable接口.在C#中,凡是实现了IDisposable接口的类,都推荐的使用using语句.如下: using (DataContext db = ...

  9. 析构函数和Dispose方法的区别

    1. 析构函数(Finalize)只能释放非托管资源, 它是由GC调用. 2. Dispose方法可以释放托管资源和非托管资源,它是由用户手动调用的. 在Dispose()中调用 GC.Suppres ...

随机推荐

  1. Visual Studio 基础设置

    重置开发环境 菜单栏中选择“工具”/“导入和导出设置”/“重置所有设置” 设置行号 菜单栏中选择“工具”/“选项”/“文本编辑器”/“行号” 全屏显示 菜单栏中选择“视图”/“全屏显示” 为程序设置版 ...

  2. go-百度贴吧-纵向爬取

    百度贴吧纵向爬取 上一个是横向爬取的,这个纵向爬取,具体怎么做的看代码 package main import ( "fmt" "io" "net/h ...

  3. 为什么要做外链建设?seo优化与发布外链速度有哪些联系?

    对于SEO员工来说,我们每天都在处理网页.从内容创建的角度来看,我们每天创建大量的URL并进入索引状态.与网站的受欢迎程度相比,网站每天也会生成大量的外部链接. 实际上,相对于链接而言,它满足了搜索引 ...

  4. 你见过的最全面的 Python 重点

    由于总结了太多的东西,所以篇幅有点长,这也是我"缝缝补补"总结了好久的东西. Py2 VS Py3 print成为了函数,python2是关键字 不再有unicode对象,默认st ...

  5. python爬取 “得到” App 电子书信息

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 静觅 崔庆才 PS:如有需要Python学习资料的小伙伴可以加点击下 ...

  6. python基础—条件语句

    一.Python基础 1.第一句python print('hello,world') Q: 后缀名可以任意? A:  导入模块时,如果不是.py后缀,会出错. 2.两种执行的方式: -python解 ...

  7. 微信小程序 setData 如何修改动态数据?

    最近这段时间在写微信小程序,有一个页面需要动态修改 data 中的数据,而这里似乎是个坑. 1.正常修改 正常修改很简单,当触发 change 事件时,数据和页面都会同时发生改变.这个也不用多说,很简 ...

  8. 【C#】学习笔记(2)委托Delegate相关

    泛型委托类型,同样是根据杨老师的视频来的. 直接上栗子

  9. 【Android】基于A星寻路算法的简单迷宫应用

    简介 基于[漫画算法-小灰的算法之旅]上的A星寻路算法,开发的一个Demo.目前实现后退.重新载入.路径提示.地图刷新等功能.没有做太多的性能优化,算是深化对A星寻路算法的理解. 界面预览: 初始化: ...

  10. 基于file上传文件的并发上传(多个文件一起上传到后台并把数据存储的同一条数据中,如 数据库字段videopath,imge。前台发送来的文件file1,file2。 videopath=file1,imge=file2)

    前台代码: <div class="tab-content"> <dl> <dt>所属栏目</dt> <dd> < ...