import java.sql.Connection;
|
import java.sql.DriverManager;
|
import java.sql.PreparedStatement;
|
import java.sql.ResultSet;
|
import java.util.ArrayList;
|
import java.util.LinkedHashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.TreeMap;
|
|
/**
|
* 只读探针:只打印某张表有差异的行——仅左库有 / 仅右库有 / 同主键但内容不同(两侧并列)。
|
*
|
* <p>用法:java DiffRows <左url> <右url> <表名> <展示列,展示列...>
|
*/
|
public class DiffRows {
|
|
public static void main(String[] args) throws Exception {
|
String table = args[2];
|
String[] columns = args[3].split(",");
|
try (Connection left = DriverManager.getConnection(args[0], "root", "123456");
|
Connection right = DriverManager.getConnection(args[1], "root", "123456")) {
|
Map<String, String> leftRows = rows(left, table, columns);
|
Map<String, String> rightRows = rows(right, table, columns);
|
System.out.println("== " + table + ":仅左库(本机 dev)有 ==");
|
for (Map.Entry<String, String> entry : leftRows.entrySet()) {
|
if (!rightRows.containsKey(entry.getKey())) System.out.println(" " + entry.getValue());
|
}
|
System.out.println("== " + table + ":仅右库(服务器)有 ==");
|
for (Map.Entry<String, String> entry : rightRows.entrySet()) {
|
if (!leftRows.containsKey(entry.getKey())) System.out.println(" " + entry.getValue());
|
}
|
System.out.println("== " + table + ":同主键内容不同 ==");
|
for (Map.Entry<String, String> entry : leftRows.entrySet()) {
|
String other = rightRows.get(entry.getKey());
|
if (other == null || other.equals(entry.getValue())) continue;
|
System.out.println(" 左 " + entry.getValue());
|
System.out.println(" 右 " + other);
|
System.out.println();
|
}
|
}
|
}
|
|
private static Map<String, String> rows(Connection connection, String table, String[] columns) throws Exception {
|
Map<String, String> lines = new TreeMap<>();
|
String selection = String.join(", ", java.util.Arrays.stream(columns).map(c -> "`" + c + "`").toList());
|
try (PreparedStatement statement = connection.prepareStatement(
|
"select id, " + selection + " from `" + table + "`");
|
ResultSet result = statement.executeQuery()) {
|
while (result.next()) {
|
StringBuilder line = new StringBuilder("#" + result.getObject(1));
|
for (int index = 0; index < columns.length; index++) {
|
Object value = result.getObject(index + 2);
|
String text = value == null ? "NULL" : String.valueOf(value);
|
if (text.length() > 70) text = text.substring(0, 70) + "…";
|
line.append(" | ").append(columns[index]).append('=').append(text);
|
}
|
lines.put(String.valueOf(result.getObject(1)), line.toString());
|
}
|
}
|
return new LinkedHashMap<>(lines);
|
}
|
}
|