Friday, December 17, 2010

How to insert multiple database rows into JTable

If you want to insert rows with data into a JTable by fetching from the database, this is the easyest way to do it.


//Statement is got through mysql connection
sql="select code,name,type from item_table"
ResultSet resultset = 
                statement.executeQuery(sql);

Vector rows=new Vector();


while(resultset.next()){
 Vector one_row=new Vector();
 one_row.add(resultset.getString('code'));
 one_row.add(resultset.getString('name'));
 one_row.add(resultset.getString('type'));

 rows.add(one_row);

}

DefaultTableModel model=new DefaultTableModel();

Iterator i=rows.iterator();
int count=0
while(i.hasNext()){
 model.insertRow(count,(Vector)i.next());
 count++;
}

//Table is the JTable instance
table.setModel(model);