正确的方法在异常事件中关闭数据库连接 [英] Correct way to close database connection in event of exception

查看:161
本文介绍了正确的方法在异常事件中关闭数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在异常,以下代码是否使连接断开?

Does the following code leave the connection open if there is an exception?

我使用的是Microsoft SQL精简版数据库。

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();
}


推荐答案

code>使用块的帮助下,您的代码中的code> SqlCeCommand ,您可以对 SqlCeConnection

The way you are handling SqlCeCommand in your code with the help of a using block, you could do the same for the SqlCeConnection.

SqlCeConnection conn;
using (conn = new SqlCeConnection(ConnectionString))
{
   conn.Open();
   using (SqlCeCommand cmd = 
       new SqlCeCommand("SELECT stuff FROM SomeTable", conn))
   {
   // do some stuff
   }
}

注意:您可以使用使用对于实现 IDisposable 的类。

Note: You can use a using block for classes that implement IDisposable.

编辑:这与

try
{
    conn = new SqlCeConnection(ConnectionString);
    conn.Open();

    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandText = "...";

    cmd.ExecuteNonQuery();
}
finally
{
    conn.Close();
}

ref: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce .sqlceconnection%28VS.80%29.aspx

这篇关于正确的方法在异常事件中关闭数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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