繁体   English   中英

使用Java代码列出特定PostgreSQL数据库中的所有表

[英]List all tables in an specific PostgreSQL database using java code

实际上我已经用谷歌搜索了一下,我需要对应的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)

如果使用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;
**************************

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

使用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指定值以获得更具体的结果。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM