简体   繁体   中英

Processing mysql records in java

I have a table with scores that contestants get after the complete a quiz. I then select the max(points) for each user and i group by user

select distinct userName, max(points) as numpoints
from tblscore
group by userName 
order by numpoints desc

this gives me the order of all the highest scores for the user. i want to store these records in an array and process it, i want to rank each record plus i want to display records where the users have a tie. How can this be achieved? how will the array be set up and processed to cater for this.

  1. Create a class (eg UserScore ) with two fields - username and points
  2. Get the ResultSet for the desired query (via a Statement )
  3. Define a List<UserScore> list = new ArrayList<UserScore>
  4. Loop the result set, using while (rs.next()) and on each iteration create a new instance of the UserScore class, set both of its fields (eg userScore.setPoints(rs.getInt("numpoints") ), and then add the object to the list
  5. If you can do with a List - go with it. If you really need an array - use list.toArray(..)

Alternatively, you can use apache commons-dbutils , and after you create the UserScore class, you just call:

List<UserScore> list = new BeanListHandler(UserScore.class).handle(resultSet);

Note that in this case your fields should be called the same way as your returned column names/aliases. You can also use the ArrayListHandler , which, instead of a list of the defined class, will give you a List<Object[]> where each column will be an element in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM