Hi guys. I'm having a bit of a 'mare trying to return some ResultSet results. Basically, my method gets the results from a database and builds a String of the information and returns it. However, I can only get the method to return the LAST constructed String, as the "result" variable keeps getting overwritten by each iteration through the ResultSet. Here is the code:

while(rs.next()){
            String date = rs.getString("When");
            String locale = rs.getString("Location");
            String ovr = rs.getString("Overview");
            String temperature = rs.getString("Temperature");
            String windDir = rs.getString("WindDirection");
            String windSpd = rs.getString("WindSpeed");
            String pressure = rs.getString("Pressure");
            result = ("Date: "+date+" Location: "+locale+ "Overview: "+ovr+" Temperature: "+temperature+" Wind Direction: "+windDir+" Wind Speed"+windSpd+" Pressure: "+pressure+"");
            
            System.out.println(result);}
        }
      catch(Exception e){e.printStackTrace();}
       try{prepStat.close();
            rs.close();
            connection.close();}
       catch(Exception e){}
            
       return result;
     }

"result" is declared at the top of the method.

So my question is, what is the easiest way to get a String returned EACH TIME it is created, instead of overwriting the same single variable? Dynamic creation of variables depending on the number of results? It doesn't seem like too hard a problem but I can work this one out.

Many thanks in advance

Recommended Answers

All 2 Replies

Return a List<String> maybe?

Or use += instead of =, maybe?

1. Create a Arraylist for returning the result(out side the while loop)
2. Create comma separated string of all the columns outside the while loop;
3. Inside while loop split this string with "," and you will get string array.
4. iterate this string array and get value (rs.getString) for all the elements.
5. inside while loop create one more String array(let say resultStr) where you will store results of step 4.
6.Add resultStr to arraylist.
7. return this arraylist

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.