java代码获取两个数据库中的表的数据并进行对比
时间: 2023-03-28 11:03:38 浏览: 166
可以使用 JDBC 连接两个数据库,分别查询需要对比的表的数据,将数据存储到两个 List 中,然后使用 Java 编写比较算法进行对比。具体实现可以参考以下代码:
```java
import java.sql.*;
import java.util.*;
public class CompareTables {
public static void main(String[] args) {
String url1 = "jdbc:mysql://localhost:3306/db1";
String url2 = "jdbc:mysql://localhost:3306/db2";
String user = "root";
String password = "123456";
String table = "table1";
List<Map<String, Object>> list1 = getData(url1, user, password, table);
List<Map<String, Object>> list2 = getData(url2, user, password, table);
if (list1.size() != list2.size()) {
System.out.println("两个表的数据不一致");
return;
}
for (int i = ; i < list1.size(); i++) {
Map<String, Object> map1 = list1.get(i);
Map<String, Object> map2 = list2.get(i);
if (!map1.equals(map2)) {
System.out.println("两个表的数据不一致");
return;
}
}
System.out.println("两个表的数据一致");
}
private static List<Map<String, Object>> getData(String url, String user, String password, String table) {
List<Map<String, Object>> list = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
while (rs.next()) {
Map<String, Object> map = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
String columnName = meta.getColumnName(i);
Object value = rs.getObject(i);
map.put(columnName, value);
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
```
阅读全文
相关推荐


















