这些语句之间有什么区别? [英] what is the difference between these statements?
本文介绍了这些语句之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以告诉我下面两个使用sqlconnection的选项之间的区别吗?
以及我该选择哪个以及为什么
选项1:
Can anybody tell me the difference between below two option for using sqlconnection
and which i should we prefer and why
option 1:
using (SqlConnection conn = new SqlConnection(connString))
{
//logic to retrive data
}
选项2:
option 2 :
SqlConnection conn = new SqlConnection(connString);
conn.open();
//logic to retrive data
非常感谢..
many thanks..
推荐答案
第一个选项调用对象的
Dispose
方法.
有关更多信息,您可以查看有关使用的MSDN主题. a>语句.
For more information you can see the MSDN topic about the using statement.
解决方案1和解决方案3很好.
我想补充一点,编译器会将using block
扩展到try...finally...
块,并在try
之前创建new instance
并在finally
块中调用Dispose
方法.
在此CodeProject文章中对此进行了很好的解释.
了解C#中的"using"语句 [ ^ ].
我认为may also be helpful
The Solution 1 and Solution 3 are good.
I want to add that theusing block
will be expanded by the compiler totry...finally...
block with the creation of anew instance
just beforetry
and callingDispose
method in thefinally
block.
It is nicely explained in this CodeProject article.
Understanding the ''using'' statement in C#[^].
I think itmay also be helpful
在第二个中,您需要在finally块中关闭连接:
In the second one you need to close the connection in the finally block:
SqlConnection conn = new SqlConnection(connString);
conn.open();
try
{
//some code
}
catch(Exception ex)
{
//Some code
}
finally
{
conn.Close();
}
但是在第一个中,您不需要关闭连接.
而且它比第二个更清晰.
然后看一下: SQL Server连接池(ADO.NET)
But in the first one you don''t need to close the connection.
And also it''s more clear than the 2st.
And look at this: SQL Server Connection Pooling (ADO.NET)
这篇关于这些语句之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文