I have a database function that retrieves data and then populates a jtable. I need to change this function so it RETURNS the data from the database within an Object[][]. How can this be done? (I’m unsure on how to store the data on each row iteration – the while loop part in the code below).
public void data() {
// clear table then load information
DefaultTableModel model=(DefaultTableModel)table.getModel();
model.getDataVector().removeAllElements();
table.repaint();
ResultSet rs=null;
Statement st=null;
try {
Class.forName("java.sql.Driver");
_con = DriverManager.getConnection(_url,_user,_pwd);
st = _con.createStatement();
String query = "SELECT * FROM table";
rs = st.executeQuery(query);
while (rs.next()) {
String d1 = rs.getString("record1");
String d2 = rs.getString("record2");
model.addRow(new Object[]{d1,d2});
}
} catch (Exception e) {
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (_con != null) {
_con.close();
}
} catch (SQLException ex) {
}
}
}
I don’t think this method is a good idea for several reasons:
Connectionoutside this method and pass it in.ResultSetandStatementshould not be member variables of the class. Make them local to the method.Just change the method to return what you want instead of
void. I wouldn’t use anObject [][]; I’d prefer a List of Maps or some other type that encapsulated a row. Use the column names as the keys in the Map.