Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all tables in an specific PostgreSQL database using java code

actually i have googled a bit and i need corresponding SELECT command to following PostgreSQL shell command :

\dt schemaname.*

i managed to get all databases with following code :

            Statement statement = (Statement) connection.createStatement();
            ResultSet rs = statement
                    .executeQuery("SELECT datname FROM pg_database");
            while (rs.next()) {
                System.out.println("DB Name : " + rs.getString(1));
           //i need another while here to list tables 
           //inside the selected database
}

i tried following statement, but no luck :

statement.executeQuery("SELECT table_schema,table_name FROM "
                                + rs.getString(1)
                                + " ORDER BY table_schema,table_name");

this is the error i am getting :

org.postgresql.util.PSQLException: ERROR: relation "template1" does not exist
  Position: 37
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
    at com.isiran.rayten.rg.db.bare.wrapper.PGWrap.main(PGWrap.java:64)
like image 748
MoienGK Avatar asked Jun 05 '26 03:06

MoienGK


1 Answers

Use the DatabaseMetaData object to query information, eg getTables(...):

DatabaseMetaData dbmd = connection.getMetaData();
try (ResultSet tables = dbmd.getTables(null, null, "%", new String[] { "TABLE" })) {
    while (tables.next()) {
        System.out.println(tables.getString("TABLE_NAME"));
    }
}

This will return all tables in the database, you may need to specify values for catalog and/or schemaPattern to get a more specific result.

like image 94
Mark Rotteveel Avatar answered Jun 06 '26 17:06

Mark Rotteveel