import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * 只读探针:把一个库的结构摘要打到标准输出,用于合并前比对目标库与本机开发库。 * *
不含任何写入语句。用法:java SchemaDigest <jdbc-url> */ public class SchemaDigest { public static void main(String[] args) throws Exception { String url = args[0]; try (Connection connection = DriverManager.getConnection(url, "root", "123456")) { String database = connection.getCatalog(); System.out.println("== SERVER =="); try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery("select version()")) { rows.next(); System.out.println(" " + rows.getString(1)); } System.out.println("== DATABASE " + database + " =="); System.out.println("== FLYWAY =="); try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery( "select version, description, success from flyway_schema_history order by installed_rank")) { while (rows.next()) { System.out.println(" " + rows.getString(1) + " | " + rows.getString(2) + " | success=" + rows.getBoolean(3)); } } catch (SQLException exception) { System.out.println(" (没有 flyway_schema_history:" + exception.getMessage() + ")"); } System.out.println("== TABLES =="); try (PreparedStatement statement = connection.prepareStatement(""" select table_name, table_rows, table_comment from information_schema.tables where table_schema = ? order by table_name """)) { statement.setString(1, database); try (ResultSet rows = statement.executeQuery()) { while (rows.next()) { System.out.println(" " + rows.getString(1) + " rows~" + rows.getLong(2) + " [" + rows.getString(3) + "]"); } } } System.out.println("== COLUMNS =="); try (PreparedStatement statement = connection.prepareStatement(""" select table_name, column_name, column_type, is_nullable, coalesce(column_default, '') from information_schema.columns where table_schema = ? order by table_name, ordinal_position """)) { statement.setString(1, database); try (ResultSet rows = statement.executeQuery()) { while (rows.next()) { System.out.println(" " + rows.getString(1) + "." + rows.getString(2) + " " + rows.getString(3) + " null=" + rows.getString(4) + " default=" + rows.getString(5)); } } } System.out.println("== INDEXES =="); try (PreparedStatement statement = connection.prepareStatement(""" select table_name, index_name, non_unique, seq_in_index, column_name from information_schema.statistics where table_schema = ? order by table_name, index_name, seq_in_index """)) { statement.setString(1, database); try (ResultSet rows = statement.executeQuery()) { while (rows.next()) { System.out.println(" " + rows.getString(1) + " " + rows.getString(2) + " unique=" + (rows.getInt(3) == 0) + " seq=" + rows.getInt(4) + " col=" + rows.getString(5)); } } } } } }