检查 SQL 服务器是否可达

Check if SQL Server is reachable

我想登录到 SQL 服务器实例 (MSSQLSERVER) 和特定数据库 (DB1)。我怎样才能用 Delphi 做到这一点?一种涵盖异常和合理警告消息的好方法?

编辑:我想看一个关于如何去做的工作示例。

Edit2:我试过这种方式,但不知道这样行不行

procedure TForm1.Button1Click(Sender: TObject);
begin
 UNIConnection1.Server := 'MSSQLSERVER';
 UNIConnection1.ProviderName := 'SQL Server';
 UNIConnection1.Username := 'username';
 UNIConnection1.Password := 'password';
 UNIConnection1.Database := 'DB1';
 UNIConnection1.LoginPrompt := False;
 try
 UNIConnection1.Connect;
 StatusBar1.SimpleText:= 'Server is running.';
 except
  on E: Exception do
      ShowMessage('Server is not reachable');
end;
end;

是这样的吗? :

procedure TForm1.Button1Click(Sender: TObject);
begin
if (button1.Caption='Connect') then
 begin
 UNIConnection1.Server := 'MSSQLSERVER';
 UNIConnection1.ProviderName := 'SQL Server';
 UNIConnection1.Username := 'username';
 UNIConnection1.Password := 'password';
 UNIConnection1.Database := 'DB1';
 UNIConnection1.LoginPrompt := False;
 try
 UNIConnection1.Connect;
 StatusBar1.SimpleText:= 'Server is running.';
 Button1.Caption:='Disconnect';
 except
  on E: Exception do
  StatusBar1.Simpletext := 'Connection error: '+e.message; 
  end;
 end else
 if (button1.Caption='Disconnect')   then
  begin
    UNIConnection1.Disconnect;
    Button1.Caption:='Connect';
    StatusBar1.SimpleText:= 'Server is not running.';
  end;
  end;

你也可以加上这个:

procedure TForm1.UniConnection1BeforeConnect(Sender: TObject);
begin
StatusBar1.SimpleText:= 'Waiting for connection.....';
end;

您还应该考虑为连接添加超时:

UniConnection.SpecificOptions.Values['ConnectionTimeout'] := '60';

编辑:我更改了代码并添加了约翰对错误消息的建议....

让 windows 完成工作。您可以创建一个 "udl" 文件并通过双击从 win 资源管理器中打开它,或者从您的程序中打开它,例如外壳执行。它带有一个配置对话框,在第二页上有一个 "test connection" 按钮。