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

时间:2013-10-28 10:00:29

标签: java sql postgresql

实际上我已经google了一下,我需要相应的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)

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

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

答案 2 :(得分:2)

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

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

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