请教:动态创建组件问题 ( 积分: 0 )

  • 主题发起人 主题发起人 corely
  • 开始时间 开始时间
C

corely

Unregistered / Unconfirmed
GUEST, unregistred user!
function GetSysId(TableName: pChar): integer;
var
ADOQuery: TADOQuery;
ADOConnection:TADOConnection;
begin
try
ADOConnection := TADOConnection.Create(nil);
ADOQuery := TADOQuery.Create(nil);
except
showmessage('´´½¨²éѯ×é¼þʧ°Ü!');
ADOConnection.Free;
ADOQuery.Free;
Exit;
end;

try
ADOConnection.Connected := False;
ADOConnection.Close;
ADOConnection.ConnectionString := '';
ADOConnection.LoginPrompt := False;
ADOConnection.Connected := True;

ADOQuery.Close;
ADOQuery.SQL.Clear;
ADOQuery.SQL.Add('SELECT next_id FROM sysdata..sysid(NOLOCK) WHERE sysid_name = ''' + TableName + '''');
ADOQuery.Open;

Result := ADOQuery.Parameters[0].Value;

ADOConnection.Free;
ADOQuery.Free;
except
Exit;
end;
end;

以上要我的代码,但在编译时老是出现以下警告,怎么解决啊?
Variable 'ADOQuery' might not have been initialized
Variable 'ADOConnection' might not have been initialized
Return value of function 'GetSysId' might be undefined
 
function GetSysId(TableName: pChar): integer;
var
ADOQuery: TADOQuery;
ADOConnection:TADOConnection;
begin
try
ADOConnection := TADOConnection.Create(nil);
ADOQuery := TADOQuery.Create(nil);
except
showmessage('´´½¨²éѯ×é¼þʧ°Ü!');
ADOConnection.Free;
ADOQuery.Free;
Exit;
end;

try
ADOConnection.Connected := False;
ADOConnection.Close;
ADOConnection.ConnectionString := '';
ADOConnection.LoginPrompt := False;
ADOConnection.Connected := True;

ADOQuery.Close;
ADOQuery.SQL.Clear;
ADOQuery.SQL.Add('SELECT next_id FROM sysdata..sysid(NOLOCK) WHERE sysid_name = ''' + TableName + '''');
ADOQuery.Open;

Result := ADOQuery.Parameters[0].Value;

ADOConnection.Free;
ADOQuery.Free;
except
Exit;
end;
end;

以上要我的代码,但在编译时老是出现以下警告,怎么解决啊?
Variable 'ADOQuery' might not have been initialized
Variable 'ADOConnection' might not have been initialized
Return value of function 'GetSysId' might be undefined
 
你的写法有点问题,所以有警告,一般这样写:


result := 0;
ADOConnection := TADOConnection.Create(nil);
ADOQuery := TADOQuery.Create(nil);

try
try
ADOConnection.Connected := False;
ADOConnection.Close;
......
except
result := -1;
Exit;
end;
finally
ADOConnection.free;
ADOQuery.free;
end;

这样写不会有警告信息。

不过按你的写法,警告归警告,程序不大会有问题的
 
try
ADOConnection := TADOConnection.Create(nil);
ADOQuery := TADOQuery.Create(nil);
except
showmessage('´´½¨²éѯ×é¼þʧ°Ü!');
ADOConnection.Free;
ADOQuery.Free;
Exit;
end;
改为
ADOConnection := TADOConnection.Create(Application);
ADOQuery := TADOQuery.Create(Application);
 
同意楼上的:
ADOConnection := TADOConnection.Create(Application);
ADOQuery := TADOQuery.Create(Application);
 
在try except之间写Create控件就会发出警告,因为在前一个try except之间Create控件表明编程者并不确定是否Create成功,万一不成功则后一个try里面使用这些控件不就出错吗,所以编译时就给警告。
应该在try之前写Create控件

Create(Application)整个应用,Create(nil)无主孤魂,Create(self)本窗口,均不会发出警告。
 
后退
顶部