2

実際に私は少しグーグルで調べましたが、次のPostgreSQLシェルコマンドに対応するSELECTコマンドが必要です:

\dt schemaname.*

次のコードですべてのデータベースを取得できました:

            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
}

私は次のステートメントを試しましたが、運がありません:

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

これは私が得ているエラーです:

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)
4

3 に答える 3

7

DatabaseMetaDataオブジェクトを使用して情報を照会します。例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"));
    }
}

これにより、データベース内のすべてのテーブルが返されます。値を指定しcatalogたりschemaPattern、より具体的な結果を取得したりする必要がある場合があります。

于 2013-10-28T10:28:04.053 に答える
4

データベースからすべてのテーブルを一覧表示するには、テーブルを読み取る必要がありますpg_catalog.pg_tables が、残念ながらデータベースにログインする必要があります。コメントを書いた場所に

//i need another while here to list tables 
//inside the selected database

テーブルのループの前に、このデータベースにログインする必要があります。

于 2013-10-28T10:19:42.753 に答える