首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 啟動/停止 SQL Server 服務的兩種實用方法

     編輯:關於C#

方法一:命令列指令(簡單快速)

在命令提示字元(需管理員權限)執行:

  • 啟動:net start mssqlserver
  • 停止:net stop mssqlserver

服務名稱 mssqlserver 為預設實例;命名實例需改為 MSSQL$實例名。

方法二:C# 程式碼控制(適用於應用程式整合)

引用 System.ServiceProcess,使用 ServiceController 類別。

完整 WinForms 範例

using System;
using System.Windows.Forms;
using System.ServiceProcess;

public class SqlServiceController : Form {
    public SqlServiceController() {
        // 啟動按鈕
        Button btnStart = new Button {
            Text = "啟動 SQL Server", Tag = "START",
            Top = 50, Left = 20, Width = 120, Parent = this
        };
        btnStart.Click += BtnClick;

        // 標題
        new Label {
            Text = "C# 啟動/停止 SQL 服務",
            ForeColor = System.Drawing.Color.Green,
            Left = 100, Top = 20, Parent = this
        };

        // 停止按鈕
        Button btnStop = new Button {
            Text = "停止 SQL Server", Tag = "STOP",
            Top = 50, Left = 150, Width = 120, Parent = this
        };
        btnStop.Click += BtnClick;

        Text = "C# SQL 服務控制";
    }

    void BtnClick(object sender, EventArgs e) {
        string action = (sender as Button).Tag.ToString();
        var sc = new ServiceController("MSSQLSERVER"); // 預設實例服務名

        try {
            if (action == "START" && sc.Status == ServiceControllerStatus.Stopped) {
                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                MessageBox.Show("SQL Server 服務啟動成功!", "提示");
            }
            else if (action == "STOP" && sc.Status != ServiceControllerStatus.Stopped) {
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
                MessageBox.Show("SQL Server 服務已停止!", "提示");
            }
            else {
                MessageBox.Show($"服務當前狀態:{sc.Status},無需操作。", "提示");
            }
        }
        catch (Exception ex) {
            MessageBox.Show($"操作失敗:{ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    [STAThread]
    static void Main() => Application.Run(new SqlServiceController());
}
程式執行畫面

關鍵點補充

  • 服務名稱:預設實例為 MSSQLSERVER,命名實例為 MSSQL$實例名,可在「服務」管理工具確認。
  • 權限需求:需管理員權限執行,否則會拋出 System.ComponentModel.Win32Exception(存取被拒)。
  • 非同步等待:使用 WaitForStatus 確認狀態變更完成,避免 UI 假死。
  • 異常處理:服務不存在、權限不足、逾時等皆需捕獲處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved