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

-




Have Questions? Post them here!