2012-03-31 55 views
0

我想從SQLite數據庫中讀取值,我有以下問題:如果API只允許您逐行進行,而沒有檢查有多少行的可能性?我想強調一個事實,即我想在最後返回一個二維數組......你會列出列表然後轉換嗎?Java:從未知大小的數據庫中讀取值

+0

有用的頁面 - http://stackoverflow.com/questions/778173/streaming-data-through -spring-jdbc-unknown-length – Coffee 2012-03-31 19:47:44

回答

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

那麼你可以建立你的二維數組:

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

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

我不需要對象,我需要2D數組 – Bober02 2012-03-31 20:04:45

+0

查看更新的答案 – 2012-03-31 20:22:28