using ResultSet.getObject(int) to populate an Object[][] array
I had to futz around with i,j to get the rows double array to match the
db table, but it's quasi-acceptable.
It was enough of a PITA that I'm sure there's a better way. To start
with, I hard coded the number of rows (9). I suppose I could iterate the
result to find the size, but then I'm iterating twice.
There's gotta be a better way. Suggestions please on how to get data
from a flat table :)
It's going to end up in a TableList for a JTable.
Whenever I look into stuff like this I see get huge results on Hibernate,
things like that which are too much right now. I'm hoping/assuming
there's something built into the API to achieve this, but a bit slicker.
thufir@arrakis:~$
thufir@arrakis:~$ cat NetBeansProjects/mysql/src/a00720398/model/
Model.java
package a00720398.model;
import a00720398.model.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.*;
@SuppressWarnings({"unchecked"})
public class Model extends Observable {
private static final Model INSTANCE = new Model();
private Connection connection = DBConnection.getInstance
().getConnection();
private Vector cars = new Vector();
private Model() {
try {
init();
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE,
null, ex);
}
}
public static Model getInstance() {
return INSTANCE;
}
private void init() throws SQLException {
ResultSet resultSet = getResultSet();
int columnCount = resultSet.getMetaData().getColumnCount();
Object[][] rows = new Object[9][columnCount];
while (resultSet.next()) {
int i = resultSet.getRow();
for (int j = 1; j < columnCount+1; j++) {
rows[i - 1][j-1] = resultSet.getObject(j);
}
}
System.out.println(Arrays.deepToString(rows));
}
ResultSet getResultSet() throws SQLException {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM
cars");
return resultSet;
}
}
thufir@arrakis:~$
thanks,
Thufir