在您的例子问题是通过表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