How to get all table names from a database using JDBC?



You can get the list of tables in the current database in MySQL using the SHOW TABLES query.

Show tables;

Following JDBC program retrieves the list of tables in the database by executing the show tables query.

Example

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ListingTables {    public static void main(String args[]) throws Exception {       //Registering the Driver       DriverManager.registerDriver(new com.mysql.jdbc.Driver());       //Getting the connection       String mysqlUrl = "jdbc:mysql://localhost/mydatabase";       Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");       System.out.println("Connection established......");       //Creating a Statement object       Statement stmt = con.createStatement();       //Retrieving the data       ResultSet rs = stmt.executeQuery("Show tables");       System.out.println("Tables in the current database: ");       while(rs.next()) {          System.out.print(rs.getString(1));          System.out.println();       }    } }

Output

Connection established...... cricketers_data customers dispatches_data employee_data myplayers sales test tutorials_data

Or, You can use the getTables() method of the DatabaseMetaData interface.

Example

import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_getTables {    public static void main(String args[]) throws Exception {       //Registering the Driver       DriverManager.registerDriver(new com.mysql.jdbc.Driver());       //Getting the connection       String mysqlUrl = "jdbc:mysql://localhost/mydatabase";       Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");       System.out.println("Connection established......");       //Retrieving the meta data object       DatabaseMetaData metaData = con.getMetaData();       String[] types = {"TABLE"};       //Retrieving the columns in the database       ResultSet tables = metaData.getTables(null, null, "%", types);       while (tables.next()) {          System.out.println(tables.getString("TABLE_NAME"));       }    } }

Output

Connection established...... cricketers_data customers dispatches_data employee_data myplayers sales test tutorials_data
Updated on: 2019-07-30T22:30:26+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements