Get all table names in a database (Views: 27)
Problem/Question/Abstract: 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... Answer: the example you find at the Delphi 5 help: MyStringList := TStringList.Create; try Session.GetTableNames('DBDEMOS', '*.db', False, False, MyStringList); { Add the table names to a list box } ListBox1.Items = MyStringList; finally MyStringList.Free; end; 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, ListBox1.Items) 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 important: 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) Const MAX_TABLES=4 {.. } database1: TDatabase; Private TableCount: Integer; AllMyTables: array[0..MAX_TABLES] of TTable; //then I created the tables at runtime for X := 0 to MAX_TABLES do begin AllMyTables[X] := TTable.Create(Form1); AllMyTables[X].database := database1 end //then called the function to retrieve all the table names without using an //Alias: database1.Session.GetTableNames(database1.DatabaseName, '', False, False, ListBox1.Items) //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 begin AllMyTables[X].TableName := ListBox1.Items[X]; AllMyTables[X].Active := True end; //of course, at the end don't forget to free the tables, since we created them //dinamically for X := 0 to MAX_TABLES do begin AllMyTables[X].Active := False; AllMyTables[X].Free end 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. |