关闭SqlConnection和SqlCommand c#
在我的DAL中,我写这样的查询:
using(SQLConnection conn = "connection string here") { SQLCommand cmd = new ("sql query", conn); // execute it blah blah }
现在我发现我没有明确关闭SQLCommand对象。 现在我知道’using’块将处理SQLConnection对象,但这还会处理SQLCommand对象吗? 如果不是我有一个严重的问题。 我必须在SQLCommand上使用’使用’成千上万行代码,或者在数百种方法上执行cmd.Close()。 请告诉我,如果使用或关闭命令将提供更好的Web应用程序内存管理?
不, using
语句不会处理命令。
您也应该using
语句包装命令,因为这将正确调用Dispose
:
using(SQLConnection conn = 'connection string here') { using(SQLCommand cmd = new ('sql query', conn)) { //execute it blah blah } }
SqlConnection
不了解SqlCommand
,因此您应该自行关闭它:
using (SqlConnection conn = new SqlConnection("connection string here")) using (SqlCommand cmd = new SqlCommand("sql query", conn)) { // execute it blah blah }
它不会处理SqlCommand
,但SqlCommand
最终将由垃圾收集器处理。 我倾向于做以下事情:
using (SqlConn conn ... ) using (SqlComm comm ... ) { conn.Open(); }
在这里堆叠using语句将处理两者。
上述就是C#学习教程:关闭SqlConnection和SqlCommand c#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/951295.html