Comparison of results in jdbc

In my java code, I have two result sets rs1 and rs2, obtained as follows:

rs1 = statement.executeQuery("select * from tableA")
rs2 = statement.executeQuery("select * from tableB")

Both tables have the same schema consisting of field identifier, name and address, and I want to compare two sets of results. Can I directly do rs1 == rs2 ?. If not, how should I compare two sets of results? Some example will be really appreciated.

thank

+5
source share
4 answers

With JDBC, you have to iterate over both objects ResultSetand compare each field in them.

If you can do this with SQL, try

select * from tableA
except -- or minus in oracle
select * from tableB

and

select * from tableB
except -- or minus in oracle
select * from tableA

Both must return an empty result.

, jOOQ ( jOOQ). jOOQ JDBC. jOOQ

Result<Record> r1 = create.fetch("select * from tableA");
Result<Record> r2 = create.fetch("select * from tableB");

:

r1 = create.fetch(rs1);
r2 = create.fetch(rs2);

if (r1.equals(r2)) {
    // the results are equal
}
else {
    // the results are not equal
}
+5

, .

    int col = 1;
    while (rs1.next() && rs2.next()) {
        final Object res1 = rs1.getObject(col);
        final Object res2 = rs2.getObject(col);
        // Check values
        if (!res1.equals(res2)) {
            throw new RuntimeException(String.format("%s and %s aren't equal at common position %d",
                res1, res2, col));
        }

        // rs1 and rs2 must reach last row in the same iteration
        if ((rs1.isLast() != rs2.isLast())) {
            throw new RuntimeException("The two ResultSets contains different number of columns!");
        }

        col++;
    }
+5

rs1 rs2 , . , .

rs1.getMetaData().

0

Since rs1 and rs2 are different objects, they indicate a different memory location, so comparing rs1 and rs2 is not correct, and you use the code below: -

while (rs.next()&& rs1.next())
{
  int userId = rs.getInt("userId")
  int userId1 = rs1.getInt("userId")
  if(userId == userId1){
   // do some thing
  }

}
0
source

All Articles