我的C#应用程序使用SMO对用户选择的SQL Server实例进行各种操作.特别是,它改变了认证模式:
ServerConnection conn = new ServerConnection(connection);
Server server = new Server(conn);
server.Settings.LoginMode = ServerLoginMode.Mixed;
Run Code Online (Sandbox Code Playgroud)
更改登录后,应重新启动更多实例.但是,我在SMO中找不到任何方式来重启所选实例.
我试图谷歌这个,但只发现了一堆枚举正在运行的服务并将其名称与SQL服务器服务名称进行比较的示例.我不喜欢这种方式,因为它容易出错并且依赖于Microsoft当前命名SQL服务器实例的方式.
有没有办法在SMO中重新启动所选实例?
添加对 的引用System.ServiceProcess。
using System.ServiceProcess;
public static void RestartService(string sqlInstanceName) {
if (string.IsNullOrEmpty(sqlInstanceName)) {
throw new ArgumentNullException("sqlInstanceName");
}
const string DefaultInstanceName = "MSSQLSERVER";
const string ServicePrefix = "MSSQL$";
const string InstanceNameSeparator = "\\";
string serviceName = string.Empty;
string server = sqlInstanceName;
string instance = DefaultInstanceName;
if (server.Contains(InstanceNameSeparator)) {
int pos = server.IndexOf(InstanceNameSeparator);
server = server.Substring(0, pos);
instance = sqlInstanceName.Substring(pos + 1);
}
serviceName = ServicePrefix + instance;
ServiceController sc = new ServiceController(serviceName, server);
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |