Trong bài toán ví dụ của bạn được truyền tên mẫu trong hàm getTables của DatabaseMetaData.
Một số cơ sở dữ liệu hỗ trợ số nhận dạng chữ hoa, một số số nhận dạng chữ thường hỗ trợ. Ví dụ oracle lấy tên bảng trong trường hợp trên, trong khi postgreSQL lấy nó trong trường hợp thấp hơn.
DatabaseMetaDeta cung cấp một phương pháp để xác định cách các cửa hàng cơ sở dữ liệu nhận dạng, có thể được trộn lẫn trường hợp, chữ hoa, chữ thường see: http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()
Từ bên dưới Ví dụ, bạn có thể nhận được tất cả các bảng và quan điểm của cung cấp tên bảng mẫu, nếu bạn chỉ muốn các bảng sau đó xóa "VIEW" khỏi mảng TYPES.
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();
}
}
}
Cảm ơn! bạn đã làm cho ngày của tôi :) –
Nếu điều này không thành công cho bạn (như nó đã làm cho tôi), bạn cần phải chắc chắn rằng người dùng cơ sở dữ liệu thực sự có thể hiển thị các bảng trên cơ sở dữ liệu. –
Nó hiển thị tất cả các bảng trong tất cả các cơ sở dữ liệu. Bạn có thể chuyển tên cơ sở dữ liệu làm tham số đầu tiên để chỉ hiển thị các bảng trong db đó. – Mahdi