【问题标题】:add objects to arraylist from resultset [duplicate]从结果集中将对象添加到arraylist [重复]
【发布时间】:2016-02-03 09:25:47
【问题描述】:

我有一个包含电影的数据库,并且我有一个类电影。我正在尝试将数据库中的电影加载到我的 GUI 中,但我似乎无法将它们放入我的数组列表中。我得到一个空异常,我看不出哪里出错了。

public ArrayList getMovies(ArrayList movieList2)
{
    movieList = movieList2;
    Connection con = null;
    try {
        con = DriverManager.getConnection(
                databaseURL, user, password);
        Statement sta = con.createStatement();


        ResultSet res = sta.executeQuery(
                "SELECT * FROM MOVIES");
        System.out.println("List of Movies: ");
        while (res.next()) {
            Movie movie = new Movie();
            movie.setTitle(res.getString((String)"Title"));
            movie.setYear(res.getInt("Yearmade"));
            movie.setGenre(res.getString("Genre"));
            movie.setDuration(res.getInt("Duration"));
            movie.setActors(res.getString("Actor"));
            movie.setDirector(res.getString("Director"));
            movieList2.add(movie);
        System.out.println(movie);
        }
        res.close();
        sta.close();
        con.close();
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
    System.out.println(movieList2);
    return movieList2;
}

这是堆栈跟踪的输出 运行:

List of Movies: 
Exception: null
null
BUILD SUCCESSFUL (total time: 0 seconds)

public static void main(String[] args) {
    controller.getMovies(movieList);
}

【问题讨论】:

  • 发布堆栈跟踪
  • 请在您的问题中包含错误堆栈。
  • 运行:电影列表:异常:null null BUILD SUCCESSFUL(总时间:0 秒)
  • movieList2 是否作为 null 传递?
  • 你初始化movieList2了吗? movieList 的类型是什么?发布调用者和堆栈跟踪。尝试初始化,movieList2 = new new ArrayList();

标签: java arraylist resultset


【解决方案1】:
Initialize movieList in caller as below,
public static void main(String[] args) {
 movieList = new ArrayList(); 
controller.getMovies(movieList);
 }  

and Removing below line in getMovies method 
 movieList = movieList2;

【讨论】:

  • 它更像一个 cmets
  • 请将其转为评论
猜你喜欢
  • 2016-08-10
  • 1970-01-01
  • 2021-05-16
  • 2016-10-31
  • 2012-12-20
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多