ID do artigo: 912426 - Última revisão: sexta-feira, 11 de maio de 2007 - Revisão: 1.2

Como detectar o status do serviço SQL Server Express ou iniciar o serviço SQL Server Express usando o Visual Basic ou Visual translation from VPE for Csharp

Dica do SistemaEste artigo aplica-se a um sistema operativo diferente do que está a utilizar. Foi desactivado o conteúdo do artigo, que pode não ser relevante para si.
Expandir tudo | Recolher tudo

Sumário

Microsoft SQL Server 2005 Express Edition é um produto baseado em serviço. Se você criar aplicativos do Microsoft Visual Studio 2005 no SQL Server 2005 Express Edition, você pode detectar o status do serviço SQL Server Express quando você iniciar o aplicativo. Você pode usar a classe ServiceController para fazer o seguinte:
  • Detecta o status do serviço SQL Server Express.
  • Inicie o serviço SQL Server Express se não for iniciado corretamente.
Observação A instalação padrão do SQL Server 2005 Express Edition usa um nome de instância do SQLEXPRESS. Esse nome de instância mapeia para o nome de serviço do MSSQL $ SQLEXPRESS.

Mais Informações

Para usar a classe ServiceController em um aplicativo de console do Visual Studio para detectar e iniciar o serviço SQL Server Express, execute essas etapas:
  1. Inicie o Visual Studio 2005.
  2. No menu arquivo , aponte para novo e, em seguida, clique em Project .
  3. Clique em Visual Basic ou Visual translation from VPE for Csharp em Project types e clique em Aplicativo de console em Visual Studio installed templates .

    Observação Por padrão, o arquivo Module1.vb é criado no projeto Visual Basic. Por padrão, o arquivo Program.cs é criado no projeto translation from VPE for Csharp Visual.
  4. Use ConsoleApplication1 como o nome na caixa nome e, em seguida, clique em OK .
  5. Adicione uma referência ao namespace "System.ServiceProcess". Para fazer isso, execute as seguintes etapas:
    1. No menu Project , clique em Adicionar referência .
    2. Clique na guia .NET , clique em System.ServiceProcess e, em seguida, clique em OK .
  6. Substitua o código existente com o código a seguir.

    Observação Substitua o código no arquivo Module1.vb no projeto Visual Basic. Substituir o código em Program.cs o arquivo no projeto translation from VPE for Csharp Visual.

    Visual Basic
    Imports System
    Imports System.ServiceProcess
    
    Module Module1
    
        Sub Main()
    
            Dim myServiceName As String = "MSSQL$SQLEXPRESS" 'service name of SQL Server Express
            Dim status As String  'service status (For example, Running or Stopped)
            Dim mySC As ServiceController
    
            Console.WriteLine("Service: " & myServiceName)
    
            'display service status: For example, Running, Stopped, or Paused
            mySC = New ServiceController(myServiceName)
            Try
                status = mySC.Status.ToString
            Catch ex As Exception
                Console.WriteLine("Service not found. It is probably not installed. [exception=" & ex.Message & "]")
                Console.ReadLine()
                End
            End Try
            Console.WriteLine("Service status : " & status)
    
            'if service is Stopped or StopPending, you can run it with the following code.
            If mySC.Status.Equals(ServiceControllerStatus.Stopped) Or mySC.Status.Equals(ServiceControllerStatus.StopPending) Then
                Try
                    Console.WriteLine("Starting the service...")
                    mySC.Start()
                    mySC.WaitForStatus(ServiceControllerStatus.Running)
                    Console.WriteLine("The service is now " & mySC.Status.ToString)
    
                Catch ex As Exception
                    Console.WriteLine("Error in starting the service: " & ex.Message)
                End Try
            End If
    
            Console.WriteLine("Press a key to end the application...")
            Console.ReadLine()
            End
        End Sub
    End Module
    translation from VPE for Csharp visual
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceProcess;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main()
            {
    
                string myServiceName = "MSSQL$SQLEXPRESS"; //service name of SQL Server Express
                string status; //service status (For example, Running or Stopped)
    
                Console.WriteLine("Service: " + myServiceName);
    
                //display service status: For example, Running, Stopped, or Paused
                ServiceController mySC = new ServiceController(myServiceName);
    
                try
                {
                    status = mySC.Status.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Service not found. It is probably not installed. [exception=" + ex.Message + "]");
                    Console.ReadLine();
    
                    return;
    
                }
    
                //display service status: For example, Running, Stopped, or Paused
                Console.WriteLine("Service status : " + status);
    
                //if service is Stopped or StopPending, you can run it with the following code.
                if (mySC.Status.Equals(ServiceControllerStatus.Stopped) | mySC.Status.Equals(ServiceControllerStatus.StopPending))
                {
                    try
                    {
                        Console.WriteLine("Starting the service...");
                        mySC.Start();
                        mySC.WaitForStatus(ServiceControllerStatus.Running);
                        Console.WriteLine("The service is now " + mySC.Status.ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error in starting the service: " + ex.Message);
    
                    }
    
                }
    
                Console.WriteLine("Press a key to end the application...");
                Console.ReadLine();
    
                return;
    
            }
    
        }
    }
  7. Pressione CTRL+F5 para executar o programa.

Referências

Para obter mais informações sobre o namespace "System.ServiceProcess", visite o seguinte site da Web Microsoft Developer Network (MSDN):
http://msdn2.microsoft.com/en-us/library/system.serviceprocess(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/system.serviceprocess(vs.71).aspx)
Para obter mais informações sobre o Visual Studio .NET, visite grupos de notícias Usenet MSDN seguintes:
http://msdn.microsoft.com/newsgroups/default.aspx (http://msdn.microsoft.com/newsgroups/default.aspx)

A informação contida neste artigo aplica-se a:
  • Microsoft Visual Studio 2005 Standard Edition
  • Microsoft Visual Studio 2005 Professional Edition
  • Microsoft SQL Server 2005 Express Edition
Palavras-chave: 
kbmt kbprb kbhowto KB912426 KbMtpt
Tradução automáticaTradução automática
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine Translation ou MT), não tendo sido portanto traduzido ou revisto por pessoas. A Microsoft possui artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais, com o objetivo de oferecer em português a totalidade dos artigos existentes na base de dados de suporte. No entanto, a tradução automática não é sempre perfeita, podendo conter erros de vocabulário, sintaxe ou gramática. A Microsoft não é responsável por incoerências, erros ou prejuízos ocorridos em decorrência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza atualizações freqüentes ao software de tradução automática (MT). Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 912426  (http://support.microsoft.com/kb/912426/en-us/ )