在您的例子問題是通過表DatabaseMetaData的getTables函數中的名稱模式。
某些數據庫支持大寫標識符,有些支持小寫字母標識符。例如,oracle以大寫形式獲取表名,而postgreSQL以小寫形式獲取。
DatabaseMetaDeta提供了一種方法來確定數據庫存儲的標識符,怎麼可以混合使用的情況下,大寫,小寫見:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()
從下面的例子,你可以提供的表名模式的所有表和視圖,如果您只需要表格,然後從TYPES數組中刪除「VIEW」。
public class DBUtility {
private static final String[] TYPES = {"TABLE", "VIEW"};
public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
try {
DatabaseMetaData meta = jdbcConnection.getMetaData();
ResultSet rs = null;
try {
if ((isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
} else if ((isQuoted && meta.storesUpperCaseQuotedIdentifiers())
|| (!isQuoted && meta.storesUpperCaseIdentifiers())) {
rs = meta.getTables(
StringHelper.toUpperCase(catalog),
StringHelper.toUpperCase(schema),
StringHelper.toUpperCase(tableNamePattern),
TYPES
);
}
else if ((isQuoted && meta.storesLowerCaseQuotedIdentifiers())
|| (!isQuoted && meta.storesLowerCaseIdentifiers())) {
rs = meta.getTables(
StringHelper.toLowerCase(catalog),
StringHelper.toLowerCase(schema),
StringHelper.toLowerCase(tableNamePattern),
TYPES
);
}
else {
rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
}
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
System.out.println("table = " + tableName);
}
}
finally {
if (rs!=null) rs.close();
}
}
catch (SQLException sqlException) {
// TODO
sqlException.printStackTrace();
}
}
public static void main(String[] args) {
Connection jdbcConnection;
try {
jdbcConnection = DriverManager.getConnection("", "", "");
getTableMetadata(jdbcConnection, "tbl%", null, null, false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
謝謝!你做了我的一天:) – 2010-05-06 11:59:16
如果你失敗了(像我這樣做),你需要確保數據庫用戶可以實際顯示數據庫上的表。 – 2012-02-13 05:18:23
它顯示所有數據庫中的所有表。您可以傳遞數據庫名稱作爲第一個參數,僅在該數據庫中顯示錶。 – Mahdi 2016-06-29 08:52:36