简体   繁体   English

如何只从java.sql.ResultSet获取第一行?

[英]How to get only the first row from a java.sql.ResultSet?

I have a ResultSet object containing all the rows returned from an sql query. 我有一个ResultSet对象包含从SQL查询返回的所有行。

I want to be able to (in the java code, NOT force it in the SQL) to be able to take a ResultSet and transform it so that it only contains 1 (the first) row. 我希望能够(在java代码中,不强制它在SQL中)能够获取ResultSet并对其进行转换,使其仅包含1(第一个)行。

What would be the way to acheive this? 实现这一目标的方法是什么? Also, is there another appropriate class (somewhere in java.sql or elsewhere) for storing just a single row rather than trimming my ResultSet? 另外,是否有另一个适当的类(在java.sql或其他地方的某个地方)只存储一行而不是修剪我的ResultSet?

Thanks! 谢谢!

For the purpose of just limiting the number of rows in a result set you can do the following: 为了限制结果集中的行数,您可以执行以下操作:

String yourQuery = "select * from some_table";
PreparedStatement statement = connection.prepareStatement(yourQuery); 
statement.setMaxRows(1); 
rs = statement.executeQuery();

As for a specific class that can hold only one row, this really depends on what you want to do with the data. 对于只能容纳一行的特定类,这实际上取决于您要对数据执行的操作。 You could for example just extract the contents of the result set and store them in an array, or if you need names as well as values a map . 例如,您可以只提取结果集的内容并将它们存储在数组中,或者如果您需要名称以及值的映射 You could also just read the data into a POJO, if you would rather work with a specific object rather than a generic data structure. 如果您希望使用特定对象而不是通用数据结构,您也可以将数据读入POJO。

You reference the need to store a single row of data, in which case I'd say that using a ResultSet is probably a bad idea as it will be typically consume database resources until closed (eg the underlying java.sql.Connection ). 你引用了存储单行数据的需要,在这种情况下我会说使用ResultSet可能是一个坏主意,因为它通常会消耗数据库资源直到关闭(例如底层的java.sql.Connection )。

Instead I'd recommend reading the first row of your ResultSet into a POJO, perhaps using Spring's JDBC utility classes (eg RowMapper ) to achieve this concisely. 相反,我建议将ResultSet的第一行读入POJO,也许使用Spring的JDBC实用程序类(例如RowMapper )来简洁地实现这一点。 Immediately after this, close the ResultSet and associated Statement and Connection (or allow Spring to do it for you). 在此之后,立即关闭 ResultSet以及关联的StatementConnection (或允许Spring为您执行此操作)。

In SQLite you can limit the number of rows doing : 在SQLite中,您可以限制执行的行数:

 "SELECT * FROM YOURTABLE ORDER BY YOURCOLUMN ASC LIMIT 3 OFFSET 3;

where LIMIT is the number of rows you want and the OFFSET the rownumber from where you want to start. 其中LIMIT是您想要的行数,OFFSET是您要从哪里开始的rownumber。

http://www.sqlitetutorial.net/sqlite-limit/ http://www.sqlitetutorial.net/sqlite-limit/

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

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