File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes ResultSet randomizing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "ResultSet randomizing" Watch "ResultSet randomizing" New topic

ResultSet randomizing

Baba Bizlowsky
Ranch Hand

Joined: Dec 15, 2003
Posts: 39
Hi everybody.
I have the following problem. I need to get a ResultSet from a database and then display all of its rows in random order. And I would like to do then in the most elegant way.
My best solution so far was to make an array of numbers from 1 to whatever the number of records in the ResultSet is, than jumble the array up with a simple mixing algorithm, and finally read the rows from the ResultSet sequentially using the number from this array and the ResultSet.absolute(int) method.
I don't think this is the most effective solution though, and I was wondering whether there was an easier way.
So, ideas anyone?
[ February 26, 2004: Message edited by: Baba Bizlowsky ]
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33102

I would copy the records from the resultset into another data structure (array, arraylist, ...) first, so you can close the resultset. You can use your mixing algorithm on this data structure and then loop through it to display the results.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
SJ Adnams
Ranch Hand

Joined: Sep 28, 2001
Posts: 925
you could find some to incorporate DBMS_RANDOM.RANDOM into your SQL?
Tom Blough
Ranch Hand

Joined: Jul 31, 2003
Posts: 263
I think SJ is recommending to use your DBs Random function to include a new columun in your output and then order by the random field:

You should then be able to iterate through your recordset in the normal way and end up with the records in random order.
Tom Blough

Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
I agree. Here's the link:
subject: ResultSet randomizing
jQuery in Action, 3rd edition