How to compare the values ​​of two results in java

I have two tables. And these tables have the same schema consisting of userid, username. I want to check if there is a common usernamein table1and table2.

 rs1 = statement.executeQuery("select username from table1")
 rs2 = statement.executeQuery("select username from table2")

My logic is:

  • while(rs1.next())
  • compare the value rs1with each value rs2.
  • Ifa match is found by typing one of the values else, type both values.

Is there any way to achieve this in java ... Please help me ... Thanks ...

+6
source share
6 answers

I would use one SQL statement:

select table1.username from table1, table2 where table1.username = table2.username

This will only return the usernames that appear in both tables, so no further processing is required.

. , table1 / table2, .

+4

, Java . , , , O (n ^ 2), . rs Set O (n) , O (n log n) O (n). , HashSet TreeSet

, .

, , . code xyz for me, for free.

0

-:

if ( A.type = B.type )
{
    PRINT same type

    if ( A.format = B.format )
    {
        PRINT same format

        if ( A.value = B.value )
        {
            PRINT same value
        }
        else
        {
            PRINT different value
        }
    }
    else
    {
        PRINT different format
    }
}
else
{
    PRINT different type
}
0

SQL IN NOT IN, - :

public boolean compareResultSets(ResultSet resultSet1, ResultSet resultSet2) throws SQLException{
        while (resultSet1.next()) {
            resultSet2.next();
            ResultSetMetaData resultSetMetaData = resultSet1.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                if (!resultSet1.getObject(i).equals(resultSet2.getObject(i))) {
                    return false;
                }
            }
        }
        return true;
    }
0
source

I give an example to solve this:

rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")

while(rs1.next()) {
// Compare till rs1 reachs its last record.
  while(rs2.next()) {
     if() {
       // Do your code here...
     }
  }

// this will move resultSet cursor to the first position.
rs2.first();
}
0
source

One way could be:

String query = "(" + query1 +") intersect ("+ query2 + ")";

Where in the intersection operation will anyway give you common columns.

PS: - I know this question is old, but it can help someone.

0
source

All Articles