比较jdbc中的结果集

Jim*_*Jim 5 java jdbc resultset

在我的java代码中,我有两个结果集rs1和rs2获得如下:

rs1 = statement.executeQuery("select * from tableA")
rs2 = statement.executeQuery("select * from tableB")
Run Code Online (Sandbox Code Playgroud)

这两个表都具有相同的模式,包括字段ID,名称和地址,我想比较两个结果集.我可以直接做rs1 == rs2吗?如果没有我应该如何比较两个结果集?一些例子将非常感激.

谢谢

Luk*_*der 5

使用JDBC,您将不得不迭代两个ResultSet对象并比较它们中的每个字段.

如果你能用SQL做到,那我就试试吧

select * from tableA
except -- or minus in oracle
select * from tableB
Run Code Online (Sandbox Code Playgroud)

select * from tableB
except -- or minus in oracle
select * from tableA
Run Code Online (Sandbox Code Playgroud)

两者都应返回空结果

如果您使用图书馆是一个选项,您可以尝试jOOQ(我为jOOQ背后的公司工作).jOOQ围绕JDBC包含许多有用的功能.使用jOOQ,您可以运行

Result<Record> r1 = create.fetch("select * from tableA");
Result<Record> r2 = create.fetch("select * from tableB");
Run Code Online (Sandbox Code Playgroud)

或者:

r1 = create.fetch(rs1);
r2 = create.fetch(rs2);
Run Code Online (Sandbox Code Playgroud)

然后

if (r1.equals(r2)) {
    // the results are equal
}
else {
    // the results are not equal
}
Run Code Online (Sandbox Code Playgroud)


gyo*_*ham 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++;
    }
Run Code Online (Sandbox Code Playgroud)