在打开或关闭之前检查SqlConnection.State [英] Checking SqlConnection.State before opening or closing

查看:280
本文介绍了在打开或关闭之前检查SqlConnection.State的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要在打开或关闭之前检查SqlConnection的状态?也就是说,是否有必要这样做:

Is it necessary to check a SqlConnection''s state before opening or closing it? That is, is it necessary to do this:

SqlConnection myConn = new SqlConnection(myConnString);
try
{
    SqlCommand myCmd = new SqlCommand(myCmdText, myConn);
    if (myConn.State != ConnectionState.Open)
        myConn.Open();
    myCmd.ExecuteNonQuery();
}
finally
{
    if (myConn.State != ConnectionState.Closed)
        myConn.Close();
}





或者我可以打电话给Open,Execute,Close吗?我的老板认为在打开它之前检查它是最好的做法,我认为它会增加不必要的代码,因为每个try块只有一个Execute语句会更好。



or can I just call Open, Execute, Close? My boss thinks it''s a best practice to check it before it is opened, I think it adds unnecessary code because it would be better to have only one Execute statement per try block.

推荐答案

除非我遗漏了明显的东西,否则,你不需要检查状态,因为你刚用new()创建它。现在,如果你使用一个普通的类并且不确定状态,那么是的,这是个好主意。
Unless I am missing something obvious, no, you do not need to check the state because you just created it with new(). Now, if you were using a common class and were uncertain of the state, then yes it would be a good idea.


你好,

你必须打开一个使用它之前的连接,您应该在运行查询后关闭连接。但是,在上面的代码中,您不需要检查连接的状态:

Hi,
You must open a connection before using it and you should close a connection after running a query. However, in the above code you do not need to check the status of the connection :
if (myConn.State != ConnectionState.Open)



因为你知道它已经关闭所以只需写一下:


as you know it is closed, so just write:

myConn.Open();





干杯



Cheers


我总是创建一个在try语句之前的新连接,但在我们的代码中可能存在多次重用连接的地方。话虽这么说,在打开或关闭它之前检查状态将(有时)阻止InvalidOperationException抛出,因此它可能是有用的。
I always create a new connection just before the try statement, but there might be places in our code where a connection is reused multiple times. That being said, checking the state before opening or closing it will (sometimes) prevent InvalidOperationException from throwing, so it could be useful for that reason.


这篇关于在打开或关闭之前检查SqlConnection.State的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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