当我启动我的PC时,Sql Server(SQLExpress)没有运行,它在我尝试在Visual Studios 2010中编译我的程序时启动.
是否可以通过C#启动它?我的问题是,如果我在没有Visual Studios的情况下使用.exe,它会告诉我Sql Server没有运行.
我会将Sql Server Windows服务的启动模式更改为自动.但你也可以在c#中做到这一点,但我不推荐它.还有其他问题,如访问安全性等.
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "net start \"Sql Server (SQLEXPRESS)\"";
process.Start();
Run Code Online (Sandbox Code Playgroud)
Sql Server(SQLEXPRESS)是您的服务名称.
以下是如何在C#中使用SMO:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Wmi;
using Microsoft.SqlServer.Management.Common;
static class SQLStart
{
public static void StartSQLService()
{
//Declare and create an instance of the ManagedComputer object that represents the WMI Provider services.
ManagedComputer mc = default(ManagedComputer);
mc = new ManagedComputer();
//Iterate through each service registered with the WMI Provider.
Service svc = default(Service);
foreach ( svc in mc.Services) {
Console.WriteLine(svc.Name);
}
//Reference the Microsoft SQL Server service.
svc = mc.Services("MSSQLSERVER");
//Stop the service if it is running and report on the status continuously until it has stopped.
if (svc.ServiceState == ServiceState.Running) {
svc.Stop();
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
while (!(string.Format("{0}", svc.ServiceState) == "Stopped")) {
Console.WriteLine(string.Format("{0}", svc.ServiceState));
svc.Refresh();
}
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
//Start the service and report on the status continuously until it has started.
svc.Start();
while (!(string.Format("{0}", svc.ServiceState) == "Running")) {
Console.WriteLine(string.Format("{0}", svc.ServiceState));
svc.Refresh();
}
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
} else {
Console.WriteLine("SQL Server service is not running.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这只是MS的VB.net示例的转换.这一切都在这里解释:http://msdn.microsoft.com/en-us/library/ms162139(v = sql.90).aspx
归档时间: |
|
查看次数: |
10749 次 |
最近记录: |