简体   繁体   中英

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

"Shows: Avenger"

You'll have to return a List<String> instead of a single 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

And don't return in the while loop, instead add to your List , eg 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM