比较两个不同表的两个结果集

时间:2013-08-24 19:33:40

标签: java sql jdbc db2

在下面的代码中,我将比较表S_R_VAL和R_VAL的两个Resultset。我需要比较S_NUMBER(来自S_R_VAL表)和S_NO(来自R_VAL表)。 比较我收到此错误“java.lang.RuntimeException:两个ResultSet包含不同数量的列!。请帮助修复此错误。

    String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
                        "  WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";

          String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +

                                     "(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";

          String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";

          String SSO =  "Select O_UID from OTG.OPTY where C_S_NO IN" +

         "( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";

          //Statement statement;

        try {

             connection = DatabaseConnection.getCon();

             statement = connection.createStatement();

             statement1 = connection.createStatement();

          ResultSet SQ = statement.executeQuery(SSQ);

          ResultSet DS = statement.executeQuery(SDS);

          ResultSet SR = statement.executeQuery(SSR);

          ResultSet SO = statement.executeQuery(SSO);


                while (rs.next() && SR.next(){

                    String res1 = rs.getString("S_NUMBER");

                    String res2 = SR.getString("S_NO");

                    StringBuffer updateQuery = new StringBuffer();


                  if (res1.equals(res2)) {
            throw new RuntimeException(String.format("%s and %s aren't equal at common position %d",
                    res1, res2));

                }else 
                {
                     throw new RuntimeException("The two ResultSets contains different number of columns!");
                }
            }

            connection.commit();

1 个答案:

答案 0 :(得分:1)

您无法重复使用相同的Statement对象,因为在每次新executeQuery()调用时,任何ResultSet如果已经打开,则会隐式关闭。

  

当生成它的Statement对象关闭,重新执行或用于从多个结果序列中检索下一个结果时,ResultSet对象会自动关闭。

查看ResultSet的JavaDocs。