一个连接到PostgreSQL并从默认数据库postgres
打印出所有表的JDBC示例
pom.xml
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
</dependencies>
PS已通过Java 8和postgresql jdbc驱动程序42.2.5测试
PrintAllTables.java
package com.mkyong.jdbc;
import java.sql.*;
public class PrintAllTables {
public static void main(String[] argv) {
System.out.println("PostgreSQL JDBC Connection Testing ~");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.err.println("Unable to find the PostgreSQL JDBC Driver!");
e.printStackTrace();
return;
}
// default database: postgres
// JDK 7, auto close connection with try-with-resources
try (Connection connection =
DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres",
"postgres", "password")) {
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet rs = metaData.getTables(null, null, "%", null)) {
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCount = rsMeta.getColumnCount();
while (rs.next()) {
System.out.println("\n----------");
System.out.println(rs.getString("TABLE_NAME"));
System.out.println("----------");
for (int i = 1; i <= columnCount; i++) {
String columnName = rsMeta.getColumnName(i);
System.out.format("%s:%s\n", columnName, rs.getString(i));
}
}
}
} catch (SQLException e) {
System.err.println("Something went wrong!");
e.printStackTrace();
return;
}
}
}
输出量
----------
pg_aggregate_fnoid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_aggregate_fnoid_index
table_type:SYSTEM INDEX
remarks:null
----------
pg_am_name_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_am_name_index
table_type:SYSTEM INDEX
remarks:null
----------
pg_am_oid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_am_oid_index
table_type:SYSTEM INDEX
remarks:null
----------
pg_amop_fam_strat_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_fam_strat_index
table_type:SYSTEM INDEX
remarks:null
----------
pg_amop_oid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_oid_index
table_type:SYSTEM INDEX
remarks:null
----------
pg_amop_opr_fam_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_opr_fam_index
table_type:SYSTEM INDEX
remarks:null
//...
----------
pg_stat_progress_vacuum
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_progress_vacuum
table_type:SYSTEM VIEW
remarks:null
----------
pg_stat_replication
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_replication
table_type:SYSTEM VIEW
remarks:null
----------
pg_stat_ssl
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_ssl
table_type:SYSTEM VIEW
remarks:null
//...
参考文献
翻译自: https://mkyong.com/jdbc/jdbc-how-to-print-all-table-names-from-a-database/