In this case I have some code which is working without problem in an existing program, but throws an excecption when I use it in a new program.
It may not be the best code, but it is working in every day use …
Function DoSQlCommandWithResultSet(const command : String;
AdoConnection : TADOConnection;
resultSet : TStringList): Boolean;
var i : Integer;
AdoQuery : TADOQuery;
begin
Result := True;
resultSet.Clear();
AdoQuery := TADOQuery.Create(nil);
try
AdoQuery.Connection := AdoConnection;
AdoQuery.SQL.Add(command);
AdoQuery.Open();
i := 0;
while not AdoQuery.eof do
begin
resultSet.Add(ADOQuery.Fields[i].Value);
AdoQuery.Next;
Inc(i);
end;
finally
AdoQuery.Free();
end;
end;
Yes, it probably needs a try/catch and the boolean result isn’t used, but it works …
…. in the previous program, but in a new one it thows an exception when called …
procedure TForm1.FormCreate(Sender: TObject);
var my_stringlist : TStringList;
i : integer;
begin
AdoConnection := TADOConnection.Create(nil);
if ConnectToDefaultDatabase(AdoConnection) = False then
MessageDlg('Agh !', mtError, [mbOK], 0);
my_stringlist := TStringList.Create();
if DoSQlCommandWithResultSet('show databases', AdoConnection, my_stringlist) = False then
MessageDlg('Urk !', mtError, [mbOK], 0);
for i := 0 to Pred(my_stringlist.Count) do
memo1.Lines.Add(my_stringlist.Strings[i]);
end; // FormCreate()
Now, here’s the interesting part … it throws the exception on Inc(i) and, if I replace that while loop with a for loop …
for i := 0 to Pred(ADOQuery.Fields.count) do
resultSet.Add(ADOQuery.Fields[i].Value);
it works just fine.
I suppose that I could just use the for loop & move on, but I would like to understand what is going wrong …. can someone explain to me? Thanks
The first thing that jumps out at me is that
and
are not semantically equivalent! When you call
Next, you’re advancing the current record in the dataset. A loop until you hitEOFwill run through each record in the dataset once. But the second loop never callsNextand doesn’t check for EOF; it’s grabbing all the fields from one record.If I had to guess what’s causing the exception in the first loop, I’d say that you’ve got more records (rows) than fields (columns) in your dataset, and so after enough iterations,
iends up atADOQuery.Fields.Countand you get an index out of bounds error.What exactly are you trying to do here?