测试连接数据库:当我第一次测试连接成功时,我故意把数据库停止掉,再次按测试连接按钮,为什么还是连接成功,谁能告诉我,为什么?用的是ADOConnection+sqlserver;
代码如下:
procedure TfrmSetupDataBase.btnTestClick(Sender: TObject);
begin
if TestConnAppAndDb then
application.MessageBox(pchar('连接成功!'),'提示',0);
end;function TfrmSetupDataBase.TestConnAppAndDb: boolean;
begin
result:=false;
if trim(edServerName.text)='' then
begin
application.MessageBox(pchar('请输入服务器地址/名称!'),'提示',0);
//edtAppname.SetFocus;
if edServerName.CanFocus then
edServerName.SetFocus;
exit;
end;
if trim(edDataBase.Text)='' then
begin
application.MessageBox(pchar('请输入数据库名!'),'提示',0);
if edDataBase.CanFocus then
edDataBase.SetFocus;
exit;
end;
ADOC.Close;
ADOC.ConnectionString:='';
ADOC.ConnectionString:=MakeConStr;
try
ADOC.Open;
// application.MessageBox(pchar('连接成功!'),'提示',0);
result:=true;
except
application.MessageBox(pchar('连接数据库服务器发生错误,请检查数据库!'),'提示',0);
edDataBase.SetFocus;
end;
end;
代码如下:
procedure TfrmSetupDataBase.btnTestClick(Sender: TObject);
begin
if TestConnAppAndDb then
application.MessageBox(pchar('连接成功!'),'提示',0);
end;function TfrmSetupDataBase.TestConnAppAndDb: boolean;
begin
result:=false;
if trim(edServerName.text)='' then
begin
application.MessageBox(pchar('请输入服务器地址/名称!'),'提示',0);
//edtAppname.SetFocus;
if edServerName.CanFocus then
edServerName.SetFocus;
exit;
end;
if trim(edDataBase.Text)='' then
begin
application.MessageBox(pchar('请输入数据库名!'),'提示',0);
if edDataBase.CanFocus then
edDataBase.SetFocus;
exit;
end;
ADOC.Close;
ADOC.ConnectionString:='';
ADOC.ConnectionString:=MakeConStr;
try
ADOC.Open;
// application.MessageBox(pchar('连接成功!'),'提示',0);
result:=true;
except
application.MessageBox(pchar('连接数据库服务器发生错误,请检查数据库!'),'提示',0);
edDataBase.SetFocus;
end;
end;
ADOC.Open;
// application.MessageBox(pchar('连接成功!'),'提示',0);
result:=true;
except
application.MessageBox(pchar('连接数据库服务器发生错误,请检查数据库!'),'提示',0);
edDataBase.SetFocus;
end;
我觉的这样写(拙见):
try
result:=true;
ADOC.Open;
// application.MessageBox(pchar('连接成功!'),'提示',0);
except
application.MessageBox(pchar('连接数据库服务器发生错误,请检查数据库!'),'提示',0);
edDataBase.SetFocus;
result:=false;
end;
function TfrmSetupDataBase.MakeConStr: string;
begin
serverName:=Trim(edServerName.Text);
lgnId:=Trim(edLgnID.Text);
lgnPwd:=trim(edPwd.Text);
intialDataBase:=trim(edDataBase.Text);
if Trim(edTimeOut.Text)='' then
lgnTimeOut:=0
else
lgnTimeOut:=strtoint(trim(Trim(edTimeOut.Text)));
Result:=adoConStr;
if ServerName<>'' then
Result:=Result+';Data Source='+ServerName ;
if lgnId<>'' then
Result:=Result+';User ID='+lgnId ;
if lgnPwd<>'' then
Result:=Result+';Password='+lgnPwd;
if lgnTimeOut>0 then
Result:=Result+';Connect Timeout='+IntToStr(lgnTimeOut);
if intialDataBase<>'' then
Result:=Result+';Initial Catalog='+intialDataBase;
end;楼上的这样写跟我这样写有什么区别,我测试了还是不行