如何只从java.sql.ResultSet获取第一行? [英] How to get only the first row from a java.sql.ResultSet?

查看:236
本文介绍了如何只从java.sql.ResultSet获取第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ResultSet对象,其中包含从sql查询返回的所有行。

I have a ResultSet object containing all the rows returned from an sql query.

我希望能够(在java代码中,不强制它在SQL)能够获取ResultSet并对其进行转换,使其仅包含1(第一行)。

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?

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?

谢谢!

推荐答案

仅用于限制 结果集 您可以执行以下操作:

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();

对于只能容纳一行的特定类,这实际上取决于你想做什么与数据。例如,您可以只提取 的内容结果集 并将它们存储在数组中,或者如果您需要名称和值 地图 。如果您希望使用特定对象而不是通用数据结构,也可以将数据读入POJO。

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.

这篇关于如何只从java.sql.ResultSet获取第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆