2

实际上我已经用谷歌搜索了一下,我需要相应的 SELECT 命令来遵循 PostgreSQL shell 命令:

\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

如果您使用psql -E,它将回显在您键入以下命令时运行的实际查询\dt

denis=# \dt public.*
********* QUERY **********
SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','s','')
      AND n.nspname !~ '^pg_toast'
  AND n.nspname ~ '^(public)$'
ORDER BY 1,2;
**************************

然后可以根据您的特定用例简化或修改这些查询。

于 2013-10-28T10:17:03.760 回答
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

要列出数据库中的所有表,您必须阅读 tablepg_catalog.pg_tables 但不幸的是,您必须登录数据库。所以在你写评论的地方

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

在循环表之前,您需要登录此数据库。

于 2013-10-28T10:19:42.753 回答