0

下面的代码是否正确关闭连接..

public static bool Hello(string sqlQuery)
        {
            SqlDataReader dataReader = null;
            var isExist = false;

            using (var aeConnection = new SqlConnection(ConnectionString))
            {
                try
                {
                    var aeCommand = new SqlCommand(sqlQuery, aeConnection)
                        {
                            CommandType = CommandType.Text
                        };

                    aeConnection.Open();
                    dataReader = aeCommand.ExecuteReader(CommandBehavior.Default);

                    while (dataReader.Read())
                    {
                       int vinCount;
                        int.TryParse(dataReader["VINCount"].ToString(), out vinCount);

                        if (vinCount == 0)
                        {
                          isExist = true;
                         }
                    }
                }
                catch (Exception ex)
                {
                   if (dataReader != null)
                   {
                       dataReader.Close();
                   }
                }
            }

            return isExist;
        }
4

1 回答 1

1

是的,它正在正确关闭连接。当退出使用块(成功完成或错误)时,它会关闭。

using 语句被编译成 try/finally 块

using (var aeConnection = new SqlConnection(ConnectionString))
            {
}

它将被视为

SqlConnection aeConnection = null;
try
{
    aeConnection  = new SqlConnection(ConnectionString);
}
finally
{
   if(aeConnection!= null)
        ((IDisposable)aeConnection).Dispose();
}
于 2013-09-12T10:25:09.037 回答