-1

I should make separate class with reading library of books, updating etc. Class books should have:

  1. parametric constructor plus override for toString()
  2. Method getAll static to read all data for DB
  3. Method getById is reading data when we give ID, also static.

but i did next:

Main.java

    try {      
        ArrayList<String[]> allBooks = Books.getAll("SELECT * FROM books");
        for (String[] izd : allBooks) {
            System.out.println("Books id: " + izd[0] + " Date of publishing: " + izd[1] + " Id of books: " + izd[2]+...);
        }
    } catch (Exception e) {
        System.out.println(e);
    }

Books.java

    static ArrayList<String[]> getAll(String stt) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException
    {
    connect();
    Statement stmt = conn.createStatement();
    stmt.executeQuery(stt);

    ResultSet rs = stmt.getResultSet();
    int columnsNum = rs.getMetaData().getColumnCount();
    ArrayList<String[]> result = new ArrayList<String[]>();

    while(rs.next())
    {
        String[] rowArr = new String[columnsNum];
            for(int i=0;i<columnsNum;i++)
                    rowArr[i]=rs.getString(i+1).toString();
            result.add(rowArr);
    }
    close();
    return result;
}

I really don't understand how.. Any help will be like :D

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mariana
  • 9
  • 1

1 Answers1

0

You are not really giving much information about your goal here, so I can only guess. I would expect something like this:

public class Book {
  private String title;
  //...

  //constructor
  public Book(String theTitle) {
    this.title = theTitle;
  }

  public static ArrayList<Book> getAll(String stt) { /* ... */ }

  public static Book getById(int id) { /* ... */ }
}

And in your getAll function you probably want something like this:

while(rs.next())
{
    Book aBook = new Book(rs.getString("title"));
    result.add(aBook);
}
SebastianH
  • 2,172
  • 1
  • 18
  • 29
  • Even is simple, doesnt mean that is stupid. I am first professor, so I know that for shure. I just started learning Java. Obviously I am misssing something in my learning. What I dont understand, for what I need constructor in this case. I know basic examples for making constructor in class and printing some data from Main.java. And I saw this function getAll from up, so what i dont understand how to fetch with using of atributes and constructor. – Mariana Feb 24 '14 at 12:06