List All Table Names of Database using Java
We can list all table names of database using java.sql.DatabaseMetaData.getTables() method. The getTables method accepts catalog, schemaPattern, tablenamePattern, types parameters and returns ResultSet where each row is table description.
Each table descriptor contain the following columns:
- String TABLE_CAT represents table catalog and can be null
- String TABLE_SCHEM represents table schema and can be null
- String TABLE_NAME represents table name
- String TABLE_TYPE represents table type. Typical types are TABLE, VIEW, SYSTEM TABLE, GLOBAL TEMPORARY, LOCAL TEMPORARY, ALIAS, SYNONYM.
- String REMARKS represents explanatory comment on the table
- String TYPE_CAT represents types catalog and can be null
- String TYPE_SCHEM represents the types schema and can be null
- String TYPE_NAME represents type name and can be null
- String SELF_REFERENCING_COL_NAME represents name of the designated identifier column of a typed table and can be null
- String REF_GENERATION specifies how values in SELF_REFERENCING_COL_NAME are created. REF_GENERATION possible values are SYSTEM, USER, DERIVED. It’s can be null also
example to list all table names of database using java
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class IsDbExist { public static void main(String[] args){ Connection con = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/mysql"; String user = "root"; String password = "password"; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, password); if(con != null){ System.out.println("list all table names of database using java"); DatabaseMetaData dbmd = con.getMetaData(); rs = dbmd.getTables(null, null, "%", null); while(rs.next()){ String tablelist = rs.getString(3); System.out.println(tablelist); } } else{ System.out.println("unable to create database connection"); } } catch(Exception ex){ ex.printStackTrace(); } finally{ if( rs != null){ try{ rs.close(); } catch(SQLException ex){ ex.printStackTrace(); } } if( con != null){ try{ con.close(); } catch(SQLException ex){ ex.printStackTrace(); } } } } }
output:-
list all table names of database using java columns_priv db event func general_log help_category help_keyword help_relation help_topic innodb_index_stats innodb_table_stats ndb_binlog_index plugin proc procs_priv proxies_priv servers slave_master_info slave_relay_log_info slave_worker_info slow_log tables_priv time_zone time_zone_leap_second time_zone_name time_zone_transition time_zone_transition_type user
In the above example We use rs.getString(3) because TABLE_NAME row is at third position, We can also write like rs.getString(“TABLE_NAME”).