以编程方式配置SQL Server TCP设置

时间:2014-01-29 04:51:52

标签: sql-server delphi configuration

每当我们为客户安装SQL Server 2008 R2时,都会有一个手动过程。我们为实例启用TCP/IPNamed Pipes协议,将TCP Dynamic Ports设置为0,并将TCP Port设置为非标准端口号(为了安全起见,故意禁用浏览器)。始终使用显式端口号(I.E. 192.168.1.100, 12345

建立连接

如何以编程方式从Delphi配置这些服务器TCP设置?

1 个答案:

答案 0 :(得分:4)

您可以使用属于ServerNetworkProtocolWMI Provider for Configuration Management Classes WMI类。

要访问此类,必须根据SQL Server版本连接到正确的命名空间。

SQL Server 2005 - ComputerManagement
SQL Server 2008 - ComputerManagement10 
SQL Server 2012 - ComputerManagement11

尝试SQL Server 2008的此示例

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;


procedure  EnableSQLServerNetworkProtocol(Const Protocol : string; EnableProtocol: Boolean);
const
  WbemUser            ='';
  WbemPassword        ='';
  WbemComputer        ='localhost';
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer(WbemComputer, 'root\Microsoft\SqlServer\ComputerManagement10', WbemUser, WbemPassword);
  FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM ServerNetworkProtocol Where ProtocolName="%s"', [Protocol]),'WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  if oEnum.Next(1, FWbemObject, iValue) = 0 then
   //if FWbemObject.Enabled<>EnableProtocol then
      Writeln('Result '+VarToStr(FWbemObject.SetEnable(EnableProtocol))); // 0 means OK
end;


begin
 try
    CoInitialize(nil);
    try
      EnableSQLServerNetworkProtocol('Tcp', True);// TCP/IP
      EnableSQLServerNetworkProtocol('Np', True); // Named Pipes
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

注意:此代码必须在安装SQL Server的同一台机器上执行,如果要远程执行此任务,则必须为WMI连接提供正确的登录参数(用户,通行证,服务器)。

要设置IP地址和端口,您可以使用ServerNetworkProtocolIPAddressServerNetworkProtocolProperty类。