如何只从 java.sql.ResultSet 中获取第一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2667913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get only the first row from a java.sql.ResultSet?
提问by llm
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!
谢谢!
采纳答案by Tendayi Mawushe
For the purpose of just limiting the number of rows in a result setyou 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 setand 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.
至于只能容纳一行的特定类,这实际上取决于您想对数据做什么。例如,您可以只提取结果集的内容并将它们存储在数组中,或者如果您需要名称和值,则使用map。如果您更愿意使用特定对象而不是通用数据结构,您也可以将数据读入 POJO。
回答by Maurice Perry
回答by Adamski
You reference the need to storea single row of data, in which case I'd say that using a ResultSet
is probably a bad ideaas it will be typically consume database resources until closed (e.g. the underlying java.sql.Connection
).
您提到需要存储单行数据,在这种情况下,我会说使用 aResultSet
可能是一个坏主意,因为它通常会消耗数据库资源直到关闭(例如底层java.sql.Connection
)。
Instead I'd recommend reading the first row of your ResultSet
into a POJO, perhaps using Spring's JDBC utility classes (e.g. RowMapper
) to achieve this concisely. Immediately after this, closethe ResultSet
and associated Statement
and Connection
(or allow Spring to do it for you).
相反,我建议将您的第一行读ResultSet
入 POJO,或许可以使用 Spring 的 JDBC 实用程序类(例如RowMapper
)来简洁地实现这一点。紧接着在此之后,关闭的ResultSet
和相关的Statement
和Connection
(或允许Spring来为你做它)。
回答by rainer
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 是您想要开始的行数。