Get all table names in a database (Views: 100)


at some point along the way, you will need to get all the table names from some database, you look at the help... not much help... you have to use an Alias and you don't want one... pretty simple anyway...


the example you find at the Delphi 5 help:

MyStringList := TStringList.Create;
Session.GetTableNames('DBDEMOS', '*.db', False, False, MyStringList);
{ Add the table names to a list box }
ListBox1.Items = MyStringList;

which would've been easier to write just:

Session.GetTableNames('DBDEMOS', '*.db', False, False, ListBox1.Items);

here they use the Session component and an Alias 'DBDEMOS', but you don't have an Alias and you don't want to bother in creating one for the installation program, you wanna use just the typical database component...
then all  you have to do is this:
drop your database component in the form, fill all the needed properties:
databasename, Drivername, etc and make this call:

database1.Session.GetTableNames(database1.DatabaseName, '', False, False,

here we use the embeded 'session' component and your own database name

both solutions give you the list of all the tables in ListBox1.Items, only in the second case you don't have an alias and you can directly specify the location of the database you need

set the third parameter to 'false' if you're not using Paradox or dBASE databases, and
set the fourth parameter to 'false' if you want only the table names

...finally an example of this... I had a situation where I had this database with a variable number of tables on it... and I had to open all of them, I had a maximum of 5 tables, so I created an array of TTables (yes, an array)

{.. }
database1: TDatabase;
TableCount: Integer;
AllMyTables: array[0..MAX_TABLES] of TTable;

//then I created the tables at runtime

for X := 0 to MAX_TABLES do
AllMyTables[X] := TTable.Create(Form1);
AllMyTables[X].database := database1

//then called the function to retrieve all the table names without using an

database1.Session.GetTableNames(database1.DatabaseName, '', False, False,

//Now I can open all the tables =o)
TableCount := ListBox1.Items.Count;
//note we save the 'TableCount' so later we
//can use it to iterate through the tables in the array
for X := 0 to TableCount do
AllMyTables[X].TableName := ListBox1.Items[X];
AllMyTables[X].Active := True

//of course, at the end don't forget to free the tables, since we created them
for X := 0 to MAX_TABLES do
AllMyTables[X].Active := False;

of course I missed some optimizations or stuff, but I just wanted to give you the idea and an example so... I hope it is useful.

<< Back to main page