简体   繁体   English

在Java中处理mysql记录

[英]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 然后,我为每个用户选择max(points)然后按用户分组

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 用两个字段创建一个类(例如UserScore )- usernamepoints
  2. Get the ResultSet for the desired query (via a Statement ) 获取所需查询的ResultSet (通过Statement
  3. Define a List<UserScore> list = new ArrayList<UserScore> 定义一个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 使用while (rs.next())循环结果集,并在每次迭代时创建UserScore类的新实例,设置其两个字段(例如userScore.setPoints(rs.getInt("numpoints") )),然后将对象添加到list
  5. If you can do with a List - go with it. 如果您可以使用List -那就去吧。 If you really need an array - use list.toArray(..) 如果您确实需要数组,请使用list.toArray(..)

Alternatively, you can use apache commons-dbutils , and after you create the UserScore class, you just call: 另外,您可以使用apache commons-dbutils ,在创建UserScore类之后,您只需调用:

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. 您还可以使用ArrayListHandler ,它代替已定义的类的列表,将为您提供List<Object[]> ,其中每一列都是数组中的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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