Comment faire pour détecter le statut du service SQL Server Express ou démarrer le service SQL Server Express à l'aide de Visual Basic ou Visual C#

Numéro d'article: 912426 - Voir les produits auxquels s'applique cet article
Agrandir tout | Réduire tout

Résumé

Microsoft SQL Server 2005 Express Edition est un produit basée sur des services. Si vous créez des applications Visual Studio 2005 sur SQL Server 2005 Express Edition, vous pouvez détecter l'état du service SQL Server Express lorsque vous démarrez l'application. Vous pouvez utiliser la classe ServiceController pour effectuer les opérations suivantes :
  • Détecter le statut du service SQL Server Express.
  • Démarrez le service SQL Server Express s'il n'est pas démarré correctement.
note L'installation par défaut de SQL Server 2005 Edition utilise un nom d'instance de SQLEXPRESS. Ce nom d'instance mappe sur le nom de service du service MSSQL $ SQLEXPRESS.

Plus d'informations

Pour utiliser la classe ServiceController dans une application de console Visual Studio pour détecter et pour démarrer le service SQL Server Express, procédez comme suit :
  1. Démarrez Visual Studio 2005.
  2. Dans le menu Fichier , pointez sur Nouveau , puis cliquez sur projet .
  3. Cliquez sur Visual Basic ou Visual C# sous types de projets , puis cliquez sur application console sous Visual Studio installés modèles .

    note Par défaut, le fichier Module1.vb est créé dans le projet Visual Basic. Par défaut, le fichier Program.cs est créé dans le projet Visual C#.
  4. Utilisez ConsoleApplication1 comme nom dans la zone Nom , puis cliquez sur OK .
  5. Ajouter une référence à l'espace de noms « System.ServiceProcess ». Pour ce faire, procédez comme suit :
    1. Dans le menu projet , cliquez sur Ajouter référence .
    2. Cliquez sur l'onglet .NET , cliquez sur System.ServiceProcess et puis cliquez sur OK .
  6. Remplacez le code existant par le code suivant.

    note Remplacez le code dans le fichier Module1.vb dans le projet Visual Basic. Remplacer le code dans le Program.cs fichier dans le projet Visual C#.

    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
    visual C#
    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;
    
            }
    
        }
    }
    Si (mySC.Status.Equals(ServiceControllerStatus.Stopped) | mySC.Status.Equals(ServiceControllerStatus.StopPending)) {essayez {Console.WriteLine (« démarrage du service... »); mySC.Start() mySC.WaitForStatus(ServiceControllerStatus.Running) ; Console.WriteLine ("le service est maintenant" + mySC.Status.ToString());} catch (exception ex) {Console.WriteLine("Error in starting the service: " + ex.Message);}} Console.WriteLine (« appuyez sur une touche pour arrêter l'application... »); Console.ReadLine() ; return;}}}
  7. Appuyez sur CTRL + F5 pour exécuter le programme.

Références

Pour plus d'informations sur l'espace de noms « System.ServiceProcess », reportez-vous au site de Web MSDN (Microsoft Developer Network) suivant :
http://msdn2.microsoft.com/en-us/library/system.serviceprocess(vs.71).aspx
Pour plus d'informations sur Visual Studio .NET, reportez-vous au groupes de discussion MSDN Usenet suivants :
http://msdn.microsoft.com/newsgroups/default.aspx

Propriétés

Numéro d'article: 912426 - Dernière mise à jour: vendredi 11 mai 2007 - Version: 1.2
Les informations contenues dans cet article s'appliquent au(x) produit(s) suivant(s):
  • Microsoft Visual Studio 2005 Standard Edition
  • Microsoft Visual Studio 2005 Professional Edition
  • Microsoft SQL Server 2005 Express Edition
Mots-clés : 
kbmt kbprb kbhowto KB912426 KbMtfr
Traduction automatique
IMPORTANT : Cet article est issu du système de traduction automatique mis au point par Microsoft (http://support.microsoft.com/gp/mtdetails). Un certain nombre d?articles obtenus par traduction automatique sont en effet mis à votre disposition en complément des articles traduits en langue française par des traducteurs professionnels. Cela vous permet d?avoir accès, dans votre propre langue, à l?ensemble des articles de la base de connaissances rédigés originellement en langue anglaise. Les articles traduits automatiquement ne sont pas toujours parfaits et peuvent comporter des erreurs de vocabulaire, de syntaxe ou de grammaire (probablement semblables aux erreurs que ferait une personne étrangère s?exprimant dans votre langue !). Néanmoins, mis à part ces imperfections, ces articles devraient suffire à vous orienter et à vous aider à résoudre votre problème. Microsoft s?efforce aussi continuellement de faire évoluer son système de traduction automatique.
La version anglaise de cet article est la suivante: 912426
L'INFORMATION CONTENUE DANS CE DOCUMENT EST FOURNIE PAR MICROSOFT SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU IMPLICITE. L'UTILISATEUR ASSUME LE RISQUE DE L'UTILISATION DU CONTENU DE CE DOCUMENT. CE DOCUMENT NE PEUT ETRE REVENDU OU CEDE EN ECHANGE D'UN QUELCONQUE PROFIT.

Envoyer des commentaires