[英]How to Return all Resultset value from method. Java
I have a database that contains: 我有一个数据库,其中包含:
title of the show:
Avenger
Deadpool
etc.
And I have a method that gets all the title of the show 我有一个获得该节目所有标题的方法
public String shows2(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ticket","root",null);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from events");
while(rs.next()){
String title = rs.getString("title");
return "Shows: " +title;
}
}catch(Exception e){
e.printStackTrace();
}
return "something";
}
But when I use this method it only returns one row/show 但是当我使用这个方法时,它只返回一行/ show
"Shows: Avenger"
You'll have to return a List<String>
instead of a single String
. 您必须返回
List<String>
而不是单个String
。
public List<String> shows2(){
List<String> result = new ArrayList<>();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ticket","root",null);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from events");
while(rs.next()){
String title = rs.getString("title");
result.add(title);
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Change public String shows2(){
to public List<String> shows2(){
so you can then return a full list of results 更改
public String shows2(){
到public List<String> shows2(){
这样您就可以返回完整的结果列表
And don't return in the while
loop, instead add to your List
, eg yourList.add(title);
并且不要在
while
循环中返回,而是添加到List
,例如yourList.add(title);
and then return at the end of the method. 然后在方法结束时返回。
hope this will help you 希望这个能对您有所帮助
public ArrayList<String> shows2() {
ArrayList<String> movieList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ticket", "root", null);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from events");
while (rs.next()) {
String title = rs.getString("title");
movieList.add("Shows: " + title);
}
} catch (Exception e) {
e.printStackTrace();
}
return movieList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.