Problem Solution Discussion Listing Tables and Databases

9.10 Listing Tables and Databases

9.10.1 Problem

You want a list of t ables in a dat abase or a list of dat abases host ed by t he MySQL server.

9.10.2 Solution

Use SHOW TABLES or SHOW DATABASES .

9.10.3 Discussion

To obt ain a list of t ables in t he current dat abase, use t his query: SHOW TABLES; However, if no dat abase has been select ed, t he query will fail. To avoid t his problem , you should eit her m ake sure t here is a current dat abase or nam e a dat abase explicit ly: SHOW TABLES FROM db_name ; Anot her form of SHOW ret urns a list of dat abases host ed by t he server: SHOW DATABASES; Be Careful with SHOW Statements Be careful how you int erpret t he result s from SHOW TABLES and SHOW DATABASES . The result from SHOW TABLES will be em pt y if you dont have perm ission t o access t he t able. The result from SHOW DATABASES m ay be em pt y as well. I f t he server was st art ed wit h t he - - safe-show -dat abase or - - skip-show- dat abase opt ion, you m ay not be able t o get m uch inform at ion wit h t he SHOW DATABASES st at em ent . I f youre looking for a dat abase- independent way t o get t able or dat abase list s and youre using Perl or Java, t ry t he following m et hods. I n Perl, DBI provides a tables funct ion t hat ret urns a list of t ables. I t works for t he current dat abase only: my tables = dbh-tables ; I n Java, you can use JDBC m et hods designed t o ret urn list s of t ables or dat abases. For each m et hod, invoke your connect ion obj ect s getMetaData m et hod and use t he result ing DatabaseMetaData obj ect t o ret rieve t he inform at ion you want . Heres how t o list t he t ables in a given dat abase: get list of tables in database named by dbName; if dbName is the empty string, the current database is used DatabaseMetaData md = conn.getMetaData ; ResultSet rs = md.getTables dbName, , , null; while rs.next System.out.println rs.getString 3; column 3 = table name rs.close ; A sim ilar procedure produces a list of dat abases: get list of databases DatabaseMetaData md = conn.getMetaData ; ResultSet rs = md.getCatalogs ; while rs.next System.out.println rs.getString 1; column 1 = database name rs.close ;

9.11 Testing Whether a Table Exists