这些语句之间有什么区别? [英] what is the difference between these statements?

查看:74
本文介绍了这些语句之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我下面两个使用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 the using block will be expanded by the compiler to try...finally... block with the creation of a new instance just before try and calling Dispose method in the finally block.

It is nicely explained in this CodeProject article.
Understanding the ''using'' statement in C#[^].

I think it may 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆