首页 > 解决方案 > 如何使用 Java 比较 2 个数据库表

问题描述

我有一个场景,我需要使用 java 比较 2 个数据库表

第一个数据库表有

id  Name Salary
1   ABC  1000
2   XYZ  2000
3   LMN  3000

第二个数据库表有

id Name Salary
4  PQR  5000
2  XYZ  2000
1  ABC  4000
3  LMN  2500

我曾使用列表进行比较,但有没有其他方法可以使用 selenium java 比较第一个表和第二个表。

我希望输出是

Second table has 4 rows while 1 table has 3 rows (or vice versa)
1st table LMN salary is 3000 and second table LMN salary is 2500

标签: javadatabasejdbc

解决方案


我会直接在 SQL 中进行要求的比较。这会更快。根据您需要的结果,有几种方法可以做到这一点。

由于您使用的是 Microsoft SQL,因此您可以通过执行以下操作来检索请求格式的行数:

SELECT 'The FirstTable has ' + cast((SELECT count(*) from FirstTable) as varchar(50)) + ' records, while the SecondTable has ' + cast((SELECT count(*) from SecondTable) as varchar(50)) + ' records';

为了获得表之间的差异,您可以执行以下操作:

SELECT * FROM FirstTable
UNION 
SELECT * FROM SecondTable
EXCEPT 
SELECT * FROM FirstTable
INTERSECT
SELECT * FROM SecondTable;

然后您可以获取 ResultSet 并比较如下条目:

while (resultSet.next())
{

  int id= rs.getInt("id");
  String name= rs.getString("name");
  int firstTableSalary = rs.getInt("salary");

  rs.next();
  int secondTableSalary = rs.getInt("salary");

  console.log(String.format("The first table salary is %d, while the second table salary is %d, name=%s, id=%d", firstTableSalary, secondTableSalary, name, id);

}

在这里准备了一个用于检查 SQL 的小提琴。


推荐阅读