Java:从未知大小的数据库中读取值

时间:2012-03-31 19:45:03

标签: java database sqlite

我正在尝试从SQLite数据库中读取值,并且我有以下问题:如果API只允许您逐行进行而不能检查有多少行,那么您将使用什么数据结构?我想强调一下,我想在最后返回一个二维数组...你是否列出了列表然后转换?

1 个答案:

答案 0 :(得分:1)

我认为最好返回您尝试获取其数据的对象列表,例如,如果您想让所有学生从数据库中获取数据,那么您可以为此创建课程:

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
}

然后您可以检索列表中的所有学生

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

修改: 要获得结果集的大小,可以调用resultset.last()然后调用resultset.getRow(),这里讨论过:

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

然后你可以构建你的2D数组:

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

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