java - 将结果集中的对象添加到数组列表

标签 java arraylist resultset

我有一个包含电影的数据库,并且我有电影作为一类。我试图将数据库中的电影加载到我的 GUI 中,但我似乎无法将它们放入我的数组列表中。我得到一个 null 异常,但我不知道哪里出了问题。

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);
}

最佳答案

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;

关于java - 将结果集中的对象添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35173008/

相关文章:

java - getParcelableExtra 返回空 NFC 标签

java - SpringTest 中的 ContextConfiguration 未加载

java - 手动将数据添加到 Java ResultSet

java - 使用手动输入将整数、 double 或字符串存储在 Comparable ArrayList 中

java - DER 编码的 RSA 公钥(八位字节字符串)

java - 如何将 ArrayList 转换为 JSON 对象

java - ArrayList 有两个元素,是否可以找到 int 元素的平均值?

arraylist - 将Array <String>转换为ArrayList <String>

java - 如何从 Jena SPARQL 结果集中获取第一个元素

java - SQLite 结果集 getString SQLException