我请你仔细阅读我的问题。
您可能知道在安装带有SQL Server Express版本的VS2005 / 2008时,SQL Server默认以Windows身份验证模式运行。您可以使用SQL Server Management Studio将模式更改为混合模式(Windows和SQL Server身份验证模式)。
与允许通过TCP / IP进行SQL Server远程连接类似,您需要使用SQL Server配置管理器,然后选择SQLEXPRESS协议,然后更改Tcp / IP选项的设置。
我需要的是使用C#以编程方式自动执行此过程。也就是说,我需要编写一个c#程序来改变模式或更改tcp / ip设置等。
任何人都能为我提供帮助,我该怎么做?
感谢您分享宝贵的时间。
答案 0 :(得分:9)
您应该使用SQL Server管理对象(SMO) - 这是一个以编程方式管理SQL Server的API。
更新:
证明有点棘手:Server.LoginMode(读/写),Server.TcpEnabled和Server.NamedPipesEnabled(遗憾的是只获取)。为了修改协议,您需要检查Microsoft.SqlServer.Management.Smo.Wmi命名空间(因此来自“另一端”):
答案 1 :(得分:5)
C#中的此功能将启用TCP / IP协议并将登录模式设置为混合模式。
参见补充信息here。
这是代码:
private static bool SetServerProperties()
{
#region standardize Connection String
string tempCatalog = "master";
string temp = @"Data Source=" + dataSource + ";Initial Catalog=" + tempCatalog + ";Integrated Security=True;MultipleActiveResultSets=True";
#endregion
SqlConnection sqlconnection = new SqlConnection(temp);
SqlCommand cmd = new SqlCommand("select @@ServerName", sqlconnection);
sqlconnection.Open();
string serverName = "";
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
serverName = dr[0].ToString();
}
catch
{
MessageBox.Show("Failed to Set SQL Server Properties for remote connections.");
}
Server srv = new Server(serverName);
srv.ConnectionContext.Connect();
srv.Settings.LoginMode = ServerLoginMode.Mixed;
ManagedComputer mc = new ManagedComputer();
try
{
Service Mysvc = mc.Services["MSSQL$" + serverName.Split('\\')[1]];
if (Mysvc.ServiceState == ServiceState.Running)
{
Mysvc.Stop();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Stopped"))
{
Mysvc.Refresh();
}
}
ServerProtocol srvprcl = mc.ServerInstances[0].ServerProtocols[2];
srvprcl.IsEnabled = true;
srvprcl.Alter();
Mysvc.Start();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Running"))
{
Mysvc.Refresh();
}
return true;
}
catch
{
MessageBox.Show("TCP/IP connectin could not be enabled.");
return false;
}
}
答案 2 :(得分:4)
如何修改注册表?
客户端协议设置存储在此处: HKEY_LOCAL_MACHINE \ SOFTWARE \微软\的MSSQLServer \客户端\ SNI9.0 查看ProtocolOrder。
身份验证模式存储在此处: HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Microsoft SQL Server \ MSSQL.1 \ MSSQLServer \ LoginMode
答案 3 :(得分:3)
通过从C#执行此存储过程,我能够以较小的占用空间执行此操作:
USE [master]
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2
GO
看起来并不多,但可以毫不费力地立即工作,无需重新启动服务。
答案 4 :(得分:2)