简体   繁体   中英

Java: reading values from the database of unknown size

I am trying to read in values from the SQLite database and I have the following question: What data structure would you use if the API only allows you to proceed row by row without the possibility of checking how many rows there are? I would like to stress the fact that I want to return a two dimensional array at the end... Would you you list of lists and then convert?

i think its better to return list of object you trying to get its data, for example if you want to get all students form database, you could make class for that:

public final class Student {
  private int id;
  private String name;
  private int age;

  public Student(int id, String name, int age) {
    this.id = id;
    this.name = name;
    this.age = age;
  }

  public int getId() {
      return this.id;
  }

  // other getter methods
}

then you can retrieve all student in list

public List<Student> getAllStudents() throws SQLException {
    List<Student> students = new ArrayList<Student>();

    String select = "SELECT * FROM students";
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery(select);

    while ( resultSet.next() ) {
        int id = resultSet.getInt(1);
        String name = resultSet.getString(2);
        int age = resultSet.getInt(3);

        Student student = new Student(id, name, age);
        students.add(student);
    }

    return students;
}

Edit : to get the size of result set, you can call resultset.last() then call resultset.getRow(), it was discussed here:

How do I get the size of a java.sql.ResultSet?

How to get a number of rows a ResultSet contains?

ResultSet resultSet = ps.executeQuery();
int rowcount = 0;
if (resultSet.last()) {
  rowcount = resultSet.getRow();
  resultSet.beforeFirst();
}

then you can build your 2D array:

    String[][] result = new String[rowCount][ColumnCount];

    int i=0;
    while (resultSet.next()) {
      // build result[i] array
      i++;
    }

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