发生异常时关闭数据库连接的正确方法
如果出现异常,以下代码是否使连接保持打开状态?
我正在使用 Microsoft SQL 精简版数据库。
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
当然更好的方法是在 try 之前声明一个连接对象,在 try 块内建立连接并在 finally 块中关闭它?
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}
Does the following code leave the connection open if there is an exception?
I am using a Microsoft SQL compact edition database.
try
{
SqlCeConnection conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
conn.Close();
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
Surely a better way would be to declare a connection object before the try, establish a connection inside the try block and close it in a finally block?
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(ConnectionString);
conn.Open();
using (SqlCeCommand cmd =
new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
{
// do some stuff
}
}
catch (Exception ex)
{
ExceptionManager.HandleException(ex);
}
finally
{
if( conn != null ) conn.Close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您在
using
块的帮助下在代码中处理SqlCeCommand
的方式,您可以对SqlCeConnection
执行相同的操作。注意:您可以对实现
IDisposable
的类使用using
块。编辑:这与
参考相同: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx
The way you are handling
SqlCeCommand
in your code with the help of ausing
block, you could do the same for theSqlCeConnection
.Note: You can use a
using
block for classes that implementIDisposable
.EDIT: This is same as
ref: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection%28VS.80%29.aspx
使用
使用
Use
Using
是处理此问题的正确方法,因为连接应始终在最后关闭。但您不仅应该检查
conn != null
,还应该检查conn
状态是否不是Closed
。is the proper way to handle this, because connection should always be closed at the end. but you should check not only that
conn != null
, but also ifconn
state is notClosed
.您应该使用
using
语句,它可以轻松处理连接关闭http://davidhayden.com/blog/dave/archive/ 2005/01/13/773.aspx
You should use
using
statement, which handles the connection closing without hassleshttp://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx
你必须尝试以下方式。
因为连接在 Final 块中关闭
You Have To Try Following Way.
Because Connection Close In Finally Block
为什么不在连接周围使用
using
以及SqlCeCommand
?Why not use a
using
around the connection as well as theSqlCeCommand
?