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); Vectorrows=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);
please explain my mistake here..
ReplyDeleteDefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
try {
while (dtm.getRowCount() > 0) {
dtm.removeRow(0);
}
Vector vbig = new Vector(); //-----big-ass vector to keep multiple tables
//
ResultSet r0 = jdbc.con().createStatement().executeQuery("select * from author");
while (r0.next()) {
//---second resultset opening to search subject name using above resultset ID
ResultSet rsubid = jdbc.con().createStatement().executeQuery("select name from subject where idsubject='" + r0.getString("subject_idsubject") + "'");
//------normally adding results from 1st resultset
Vector v0 = new Vector();
v0.add(r0.getString("employee_idemployee"));
v0.add(r0.getString("name"));
v0.add("Author");
//--special addition of subject name
while (rsubid.first()) {
v0.add(rsubid.getString("name"));
}
rsubid.close();//--finish special addition of subject name;
//----second resultset closed
//-----adding first table's vector to big vector
System.out.println("first vector addition");
vbig.add(v0);
}
r0.close();
//
//
ResultSet r1 = jdbc.con().createStatement().executeQuery("select * from editor");
while (r1.next()) {
Vector v1 = new Vector();
v1.add(r1.getString("employee_idemployee"));
v1.add(r1.getString("name"));
v1.add("Editor");
v1.add("---");
//-----adding second table's vector to big vector
System.out.println("second vector addition");
vbig.add(v1);
}
r1.close();
//
//----adding big vector to table
dtm.addRow(vbig);
System.out.println("big vector added to table");
System.gc();
System.out.println("author_editor table refreshing complete");
} catch (Exception e) {
System.out.println("error refreshing author_editor table");
System.out.println(e);
}
oh fine, i got it, now i see why have the iterator .. thanks a lot btw,
ReplyDeletesend regards to lakshika and aunty too :)
can you give me the syntax of inserting values from jtable to database in netbeans
ReplyDelete