How to list all tables using Java JDBC


If you want to list or print all the tables within a database using Java JDBC code, you may execute the show tables query using the Statement,

Query:
show tables;
Show Tables Query
Java JDBC Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class JDBCListAllTablesExample {
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String url ="jdbc:mysql://localhost:3306/my_uat";
        String userName="root";
        String password ="root123";
        String insertQuery ="show tables";
        Connection connection = DriverManager.getConnection(url,userName,password);
        PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
        ResultSet resultSet = preparedStatement.executeQuery();

        while(resultSet.next()) {
            System.out.println(resultSet.getString(1));
        }
    
    }
}
Output:

student_marks
students

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap