Formation of a variable name with strings + integer and calling functions

First off, I'm new to this, and the question might be silly. Anyway, I have such a procedure:

procedure Tform1.QueryChange(sqltext : String; query : Integer); begin if query = 1 then begin ADOQuery1.Close; ADOQuery1.SQL.Clear; ADOQuery1.SQL.Add(sqltext); ADOQuery1.Open; end; if query = 2 then begin ADOQuery2.Close; ADOQuery2.SQL.Clear; ADOQuery2.SQL.Add(sqltext); ADOQuery2.Open; end; 

I would like to remove if blocks and make one concatenated code:

 ADOQuery+query.Close; (know that looks very silly) ADOQuery+query.SQL.Clear; ADOQuery+query.SQL.Add(sqltext); ADOQuery+query.Open; 

My goal is when query code = 1 will use ADOQuery1.Close; etc. when query code = 2 will use ADOQuery2.Close;

+4
source share
3 answers

Instead of creating variables ADOQuery1 , ADOQuery2 , ADOQuery3 , etc. of type TADOQuery create an array:

 ADOQueries: array of TADOQuery; 

Then set the number of elements in it when you know how much they will be:

 SetLength(ADOQueries, NumberOfQueries); 

Alternatively, if you know from the beginning how many elements there will be, you can define ADOQueries instead of a static array:

 ADOQueries: array[0..7] of TADOQuery; 

Now you can do

 procedure TForm1.QueryChange(sqltext: String; query: Integer); begin ADOQueries[Query].Close; ADOQueries[Query].SQL.Clear; ADOQueries[Query].SQL.Add(sqltext); ADOQueries[Query].Open; end; 
+6
source

You can create a local variable that references the TADOQuery object that you want to work with. Like this:

 var ADOQuery: TADOQuery; begin if query=1 then ADOQuery := ADOQuery1 else if query=2 then ADOQuery := ADOQuery2; ADOQuery.Close; ADOQuery.SQL.Clear; ADOQuery.SQL.Add(sqltext); ADOQuery.Open; end; 
+8
source

Another way you can do this is with the FindComponent method, that is, provided that the form owns the request components

 procedure Tform1.QueryChange(sqltext : String; query : Integer); var cmp: TComponent; Query: TADOQuery; begin cmp := FindComponent('ADOQuery' + IntToStr(query)); if cmp <> nil then begin Query := cmp as TADOQuery; Query.Close; ... end; end; 
+3
source

Source: https://habr.com/ru/post/1482345/


All Articles