Moi*_*nGK 1 java sql postgresql
实际上我已经google了一点,我需要相应的SELECT命令来跟随PostgreSQL shell命令:
\dt schemaname.*
Run Code Online (Sandbox Code Playgroud)
我设法使用以下代码获取所有数据库:
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
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下声明,但没有运气:
statement.executeQuery("SELECT table_schema,table_name FROM "
+ rs.getString(1)
+ " ORDER BY table_schema,table_name");
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
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)
Run Code Online (Sandbox Code Playgroud)
如果您使用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;
**************************
Run Code Online (Sandbox Code Playgroud)
然后可以根据您的特定用例简化或修改这些查询.
使用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"));
}
}
Run Code Online (Sandbox Code Playgroud)
这将返回数据库中的所有表,您可能需要指定值catalog和/或schemaPattern获得更具体的结果。