Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all table names from a database?

I'd like to retrieve all table names from a database schema, and, if possible, get all table starting with a specified prefix.

I tried using JDBC's connection.getMetaData().getTables() but it didn't work at all.

Connection jdbcConnection = DriverManager.getConnection("", "", ""); DatabaseMetaData m = jdbcConnection.getMetaData(); ResultSet tables = m.getTables(jdbcConnection.getCatalog(), null, "TAB_%", null); for (int i = 0; i < tables.getMetaData().getColumnCount(); i++) {    System.out.println("table = " + tables.getMetaData().getTableName(i)); } 

Could someone help me on this?

like image 803
Maxime ARNSTAMM Avatar asked May 06 '10 10:05

Maxime ARNSTAMM


People also ask

How do I get a list of table names in a database?

In MySQL, there are two ways to find the names of all tables, either by using the "show" keyword or by query INFORMATION_SCHEMA. In the case of SQL Server or MSSQL, You can either use sys. tables or INFORMATION_SCHEMA to get all table names for a database.

How can we see all the tables from the database?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.

How do I get a list of table names in MySQL?

The syntax to get all table names with the help of SELECT statement. mysql> use test; Database changed mysql> SELECT Table_name as TablesName from information_schema.


2 Answers

You need to iterate over your ResultSet calling next().

This is an example from java2s.com:

DatabaseMetaData md = conn.getMetaData(); ResultSet rs = md.getTables(null, null, "%", null); while (rs.next()) {   System.out.println(rs.getString(3)); } 

Column 3 is the TABLE_NAME (see documentation of DatabaseMetaData::getTables).

like image 67
Peter Lang Avatar answered Sep 23 '22 22:09

Peter Lang


 public void getDatabaseMetaData()     {         try {              DatabaseMetaData dbmd = conn.getMetaData();             String[] types = {"TABLE"};             ResultSet rs = dbmd.getTables(null, null, "%", types);             while (rs.next()) {                 System.out.println(rs.getString("TABLE_NAME"));             }         }              catch (SQLException e) {             e.printStackTrace();         }     } 
like image 32
Rohit Avatar answered Sep 19 '22 22:09

Rohit