How to add new rows into a jTable from database while button click without clearing existing rows in jTable?
I tried lot of ways. But no success. Help
String SQL = "SELECT name,price FROM items WHERE ID = ' "+jTextField1.getText()+" ' ";
pst = Conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUnits.resultSetToTableModel(rs));
Edit:- With the help of all answers i change the code into below code, But OK . But here i get a error in DefaultTableModel
String sql = "SELECT name,price FROM items WHERE ID = '"+jtxt1.getText()+"'";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
DefaultTableModel model = new DefaultTabelModel(new String[]{"Name","Price"},0);
Vector row = new Vector();
while(rs.next())
{
String d = rs.getString("name");
String e = rs.getString("price");
row.add(new Object[]{d,e});
model.addRow(row);}
New Code
String sql = "SELECT name,price FROM items WHERE ID = '"+jtxt1.getText()+"'";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
Vector row = new Vector();
row.add(rs);
model.addRow(row);
Newest Code
ResultSetMetaData metaData;
public void metaData() throws SQLException {
this.metaData = rs.getMetaData();
}
String sql = "SELECT name,price FROM items WHERE ID = '"+jtxt1.getText()+"'";
pst = conn.prepareStatement(sql);
rs=pst.executeQuery();
int columnCount = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
System.out.println("ColumnNames "+columnNames );
}
DefaultTableModel datamodel = new DefaultTableModel(columnNames, 0);
jTable1.setModel(datamodel);
while (rs.next()) {
Vector<String> vector = new Vector<String>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getString(columnIndex));
}
datamodel.addRow(vector);
}
**But here i get a NullpointException error ! And how do i select jTable1 as the table in above code ?