简体   繁体   English

在ResultSet Java中对数据进行排序

[英]Sorting data in ResultSet Java

I have obtained a ResultSet for some query, eg: 我已经获得了一些查询的ResultSet,例如:

select * from students order by roll 

Now, is it possible to perform an equivalent of query 现在,是否可以执行等效查询

Select * from students order by dob;`

on the ResultSet ? ResultSet上

As rule of thumb (well, almost) everything that can be done in the DB should be done there, so you should sort your data in the DB using the ... ORDER BY <column1>, <COLUMN2>... ASC/DESC 根据经验(几乎),可以在数据库中完成的所有操作都应在此完成,因此您应该使用... ORDER BY <column1>, <COLUMN2>... ASC/DESC对数据库中的数据进行排序... ORDER BY <column1>, <COLUMN2>... ASC/DESC

But if for some reason you cannot do that you should extract all the data from the RS into a collection (and may be map your data to domain objects) and sort it using the Collections.sort() method with an appropriate Comparator 但是,如果由于某种原因您不能这样做,则应该将RS中的所有数据提取到一个集合中(并可能将数据映射到域对象),并使用带有适当ComparatorCollections.sort()方法对其进行排序

It will be very not recommended to do the Sort after the query (ie. When you're getting the ResultSet). 不建议在查询后进行排序(即,当您获得ResultSet时)。 You should always aim to do actions on the SQL Server rather on the code itself. 您应该始终以在SQL Server而不是代码本身上为目标。

ResultSet are some kind of Iteration objects, that means that you can only move one by one. ResultSet是某种Iteration对象,这意味着您只能一个一个地移动。 Thus, in order to Sort it, you first need to shift the data into a Collection and only then use Sorting on it. 因此,为了对其进行排序,您首先需要将数据移到一个Collection中,然后才对它使用Sorting。 Compare to SQL Sorting this is overhead and can be avoided. 与SQL排序相比,这是开销,可以避免。

Get an ArrayList from your ResultSet by iterating over your result and adding it to aa new list. 通过遍历结果并将其添加到新列表中,从ResultSet获取ArrayList Then use Collections.sort(Collection, Comparator) to sort your result 然后使用Collections.sort(Collection, Comparator)对结果进行排序

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

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