Search code examples
javasqlresultset

Inject a string at the end of every row of a ResultSet except the last one


I am querying a table and it returns an unknown number of rows. I'm trying to build a dynamic query that goes something like this:

sql_string = "select * from table where ";
while (res.next()) {
    sql_string += res.getString(1) + "union"
}
etc etc.

Essentially, res.next() refers to a previously executed query, and I am trying to build a query by substituting values from it's resultset. The final query should be something like:

select * from table where cond1 UNION select * from table where cond2, but it returns something like:

select * from table where cond1 UNION select * from table where cond2 UNION

What is the best way to achieve the desired result? Thanks!


Solution

  • Well, there is ResultSet.isLast() function you could call to check if your suffix should be appended, but it is optional (might not be implemented by your JDBC provider), and also may be expensive.

    A better idea may be to append the extra stuff at the beginning of the loop rather than at the end:

    String originalSql = sql_string + " ";
    String append = " "; 
    while(res.next()) {
       sql_string += append + res.getString(1);            
       append = " union " + originalSql;
    }