浅析C#启动停止SQL数据库服务之方法

C#启动停止SQL数据库服务方法之一:

在命令行里填写命令:net start/stop mssqlserver

C#启动停止SQL数据库服务方法之二:

通过C#代码实现;

 
 
 
 
  1. using System;     
  2. using System.Windows.Forms;     
  3. using System.ServiceProcess;     
  4. class Test : Form     
  5. {     
  6.     Test()     
  7.     {     
  8.          //启动按钮;     
  9.         Button btn1 = new Button();     
  10.         btn1.Parent = this;     
  11.         btn1.Text = "启动 SQL Server";     
  12.         btn1.Tag = "START";     
  13.         btn1.Top=50;     
  14.         btn1.Left = 20;     
  15.         btn1.Width = 120;     
  16.         btn1.Click += new EventHandler(BtnClick);     
  17.              
  18.          //标题;     
  19.         Label la=new Label ();     
  20.         la.Text="C#启动SQL服务";     
  21.         la.ForeColor=System .Drawing.Color.Green;     
  22.         la.Left=100;     
  23.         la.Top=20;     
  24.         la.Parent=this;     
  25.              
  26.          //关闭按钮;     
  27.         Button btn2 = new Button();     
  28.         btn2.Parent = this;     
  29.         btn2.Text = "停止 SQL Server";     
  30.         btn2.Tag = "STOP";     
  31.         btn2.Left = btn1.Right + 10;     
  32.         btn2.Top=50;             
  33.         btn2.Width = 120;     
  34.         btn2.Click += new EventHandler(BtnClick);     
  35.              
  36.         this.Text="C#启动SQL服务";     
  37.     }     
  38.     void BtnClick(object sender, EventArgs e)     
  39.     {     
  40.         string s = (sender as Button).Tag.ToString();     
  41.         ServiceController sc = new ServiceController("MSSQLSERVER");     
  42.         if (s == "START" && sc.Status.Equals(ServiceControllerStatus.Stopped))     
  43.         {     
  44.             sc.Start();     
  45.             MessageBox.Show("SQL数据库服务启动成功!","提示信息");     
  46.         }     
  47.         if (s == "STOP" && !sc.Status.Equals(ServiceControllerStatus.Stopped))     
  48.         {     
  49.             sc.Stop();     
  50.             MessageBox.Show("SQL数据库服务已经关闭!","提示信息");     
  51.         }     
  52.     }     
  53.     static void Main()     
  54.     {     
  55.         Application.Run(new Test());     
  56.     }     
  57. }   

效果如图:

 

C#启动停止SQL数据库服务的相关内容就介绍到这里,希望大家喜欢。

【编辑推荐】

  1. 学习C#消息:循序渐进
  2. 解惑答疑:C#委托和事件
  3. 学习C#实现HTTP协议:多线程文件传输
  4. 进一步接触C#委托与事件
  5. 浅析四种C#转换的区别
THE END