如何在点击按钮时从数据库向jTable添加新行而不清除jTable中的现有行?
我尝试了很多方法。但没有成功。帮助
String SQL = "SELECT name,price FROM items WHERE ID = ' "+jTextField1.getText()+" ' ";
pst = Conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUnits.resultSetToTableModel(rs));
编辑: - 在所有答案的帮助下,我将代码更改为下面的代码,但是 好 。但是我在 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);}
新代码
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);
最新代码
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);
}
**但是在这里我得到一个NullpointException错误!我如何选择jTable1作为上面代码中的表?
答案 0 :(得分:1)
处理ResultSet中的每一行数据并创建一个Vector和use this method以将数据插入表模型中。您正在创建新的表模型并将其设置在表中,带有数据的旧模型将丢失。
在评论中发出以下请求后:
这是一种方法。
fs.createReadStream(inputFile)
.pipe(csv())
.on('data', function(data){
console.log(data);
})
.on('end', function(){
console.log('Read finished');
})