当我启动我的PC时,Sql Server (SQLExpress)没有运行,当我试图在Visual Studios2010中编译我的程序时,它启动了。
可以通过C#启动吗?我的问题是,如果我使用没有Visual Studios的.exe,它会告诉我Sql Server没有运行。
发布于 2011-10-20 23:04:20
我会将Sql Server Windows服务的启动模式更改为自动。但是你也可以在c#中做到这一点,但我不推荐你这样做。还有其他的问题,比如访问安全等等。
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "net start \"Sql Server (SQLEXPRESS)\"";
process.Start();Sql Server (SQLEXPRESS)是您的服务的名称。
发布于 2011-10-20 23:29:10
下面是如何在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.");
}
}
}这只是MS的VB.net示例的转换。所有的解释都在这里:http://msdn.microsoft.com/en-us/library/ms162139(v=sql.90).aspx
发布于 2011-10-20 23:04:54
不要在代码中这样做。这是非常罕见的,这是必要的/有用的。不要重复发明轮子:
在管理工具中查看计算机的服务管理器。您应该在那里看到您的SQL Server Express实例。您可以从那里手动启动它,也可以将其设置为从服务属性中的设置自动启动。在Startup Type组合框中将其设置为Automatic。
后续:正如已经提出的,有许多不同的方法来启动服务器/服务。我看到的非服务建议的问题是,您将引入不必要的安全性、配置和其他管理开销。作为服务运行的SQL Server是一个广为人知的范例。再说一次,不要重复发明轮子。
https://stackoverflow.com/questions/7837957
复制相似问题