我有一个包含以下内容的数据库:
title of the show:
Avenger
Deadpool
etc.
我有一个方法可以获得节目的所有标题
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";
}
但是当我使用这个方法时,它只返回一行/ show
"Shows: Avenger"
答案 0 :(得分:3)
您必须返回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;
}
答案 1 :(得分:0)
将public String shows2(){
更改为public List<String> shows2(){
,以便您可以返回完整的结果列表
并且不会在while
循环中返回,而是添加到您的List
,例如yourList.add(title);
然后在方法结束时返回。
答案 2 :(得分:0)
希望这会对你有所帮助
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;
}