moro_920
moro_920

Reputation: 1

How to create and access arraylist(in java) of item rows from mysql database?

I have a clas BookBean, where I have the fields from database: id, title and author. I want to create an ArrayList bookList of BookBean type, where to get each row from database. For example, bookList[0] should point to the first row from database: id=1, title=first title, author=first author.

I have tried declaring a BookBean variable and an ArrayList:

static ArrayList<BookBean> listBooks = new ArrayList<>();
static BookBean bookBean = new BookBean(1,"title", "author");

This is my function where I get items from database. I can access the items inside the ResultSet search, but not outside it. How can I store the items into the arraylist properly?

public static void generateBookList(){
        try {
            Connection connection = ConnectToDatabase.createConnection();
            if (connection != null) {
                PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from book ");
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    bookBean.setId(resultSet.getInt("id_book"));
                    bookBean.setTitle(resultSet.getString("title"));
                    bookBean.setAuthor(resultSet.getString("author"));
                    listBooks.add(bookBean);

                    System.out.println(listBooks.get(0).getId());
                    System.out.println(listBooks.get(0).getTitle());
                    System.out.println(listBooks.get(0).getAuthor());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Upvotes: 0

Views: 116

Answers (1)

SamratV
SamratV

Reputation: 226

You need to create new OBJECT of BookBean everytime you insert into ArrayList.

public static void generateBookList(){
        try {
            Connection connection = ConnectToDatabase.createConnection();
            if (connection != null) {
                PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from book ");
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    //You are actually using the same object again and again.
                    // Following line is important.
                    BookBean x = new BookBean(resultSet.getInt("id_book"), resultSet.getString("title"), resultSet.getString("author"));
                    listBooks.add(x);

                    System.out.println(listBooks.get(0).getId());
                    System.out.println(listBooks.get(0).getTitle());
                    System.out.println(listBooks.get(0).getAuthor());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Upvotes: 1

Related Questions