利用 DatabaseMetaData 接口,無需手寫 SQL 即可動態獲取數據庫結構信息,適用於代碼生成器、數據字典工具、遷移校驗等場景。
| 方法 | 用途 | 關鍵返回列 |
|---|---|---|
getTables() | 獲取表/視圖列表 | TABLE_NAME(3), TABLE_TYPE(4) |
getColumns() | 獲取指定表列信息 | COLUMN_NAME(4), TYPE_NAME(6), COLUMN_SIZE(7) |
getPrimaryKeys() | 獲取主鍵列 | COLUMN_NAME(4), KEY_SEQ(5) |
getIndexInfo() | 獲取索引信息 | INDEX_NAME(6), COLUMN_NAME(9) |
public List<String> getAllTableNames(Connection conn, String schema) throws SQLException {
List<String> tables = new ArrayList<>();
try (ResultSet rs = conn.getMetaData().getTables(schema, null, "%", new String[]{"TABLE"})) {
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME")); // 列索引 3
}
}
return tables;
}
關鍵參數:
catalog:MySQL 中對應 schema(數據庫名),傳 null 表示當前連接庫schemaPattern:MySQL 中通常傳 nulltableNamePattern:"%" 匹配所有types:new String[]{"TABLE"} 僅獲取表,排除視圖/系統表public List<String> getColumnNames(Connection conn, String schema, String tableName) throws SQLException {
List<String> columns = new ArrayList<>();
try (ResultSet rs = conn.getMetaData().getColumns(schema, null, tableName, "%")) {
while (rs.next()) {
columns.add(rs.getString("COLUMN_NAME")); // 列索引 4
}
}
columns.sort(String::compareToIgnoreCase); // Java 端排序
return columns;
}
-- 獲取指定庫所有表名 SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'your_db' AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME; -- 獲取指定表列名(按名排序) SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'your_db' AND TABLE_NAME = 'your_table' ORDER BY ORDINAL_POSITION; -- 或 ORDER BY COLUMN_NAME
@Autowired
private DataSource dataSource;
public List<String> getTables() {
return jdbcTemplate.queryForList(
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'",
String.class, "your_db");
}
public List<Map<String, Object>> getColumns(String tableName) {
return jdbcTemplate.queryForList(
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT " +
"FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",
"your_db", tableName);
}
// 判斷表是否存在
public boolean tableExists(Connection conn, String schema, String tableName) throws SQLException {
try (ResultSet rs = conn.getMetaData().getTables(schema, null, tableName, new String[]{"TABLE"})) {
return rs.next();
}
}
// 判斷列是否存在
public boolean columnExists(Connection conn, String schema, String table, String column) throws SQLException {
try (ResultSet rs = conn.getMetaData().getColumns(schema, null, table, column)) {
return rs.next();
}
}
getTables 返回的名稱與實際存儲一致,建議統一小寫information_schema 有 SELECT 權限(通常默認有)jdbc:mysql://host:3306/your_db 可省去傳 schema 參數掌握 DatabaseMetaData 與 information_schema 雙重技能,靈活應對各類元數據需求。