如何从java中的结果集中返回多行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20463325/
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 return multiple rows from result set in java?
提问by Subbarao Gaddam
I have a query, which returns multiple rows to result set. now i need to return total rows in to the application which calling this function.
我有一个查询,它返回多行到结果集。现在我需要将总行数返回到调用此函数的应用程序中。
I tried with this code:
我尝试使用此代码:
final PreparedStatement ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
result = rs.getInt(1);
}
by this code i am able to return only one value. Now i want to return multiple rows
通过这段代码,我只能返回一个值。现在我想返回多行
回答by Ajay
Try This code Hope this helps you
试试这个代码希望这对你有帮助
final PreparedStatement ps = con.prepareStatement(query);
最终 PreparedStatement ps = con.prepareStatement(query);
ResultSet rs=ps.getResutlSet();
ResultSetMetaData rsmd=rs.getMetaData();
for(int i=1;i<=rsmd.getRowCount();i++){
String resut=rsmd.getString(i);
}
回答by SpringLearner
In this line result = rs.getInt(1);
result is getting replaced each time with a new value.
A good alternate would be to store the values in a list then return the list provided the method return type should be List
在这一行中, result = rs.getInt(1);
结果每次都被一个新值替换。一个好的替代方法是将值存储在列表中,然后返回列表,前提是方法返回类型应为 List
回答by Aniket Kulkarni
Create ArrayListof Integer
and add result
, return that array list.
创建的ArrayList中Integer
,并添加result
,返回数组列表。
ArrayList<Integer> resultList = new ArrayList<Integer>();
while (rs.next()) {
result = rs.getInt(1);
resultList.add(result);
}
return resultList;
回答by Lijo
Result set will contain the number of rows returned by the query. Using result set object.next we can easily go through this rows of data. In the above code you have only getting one value. if result set contain more than one value. then get this values using the index.
结果集将包含查询返回的行数。使用结果集 object.next 我们可以轻松浏览这行数据。在上面的代码中,您只能获得一个值。如果结果集包含多个值。然后使用索引获取此值。
while(rs. next)
{
result1=rs.getInt(1);//this will get the two value in each row.
result2=rs.getInt(2);
}
if there are are more than one value then use that much index rs.getint(1)
....rs.getInt(10)
also for Strings rs.getString(2)
如果有多个值,则使用那么多索引rs.getint(1)
......rs.getInt(10)
也用于字符串rs.getString(2)