gpt4 book ai didi

java - 如何在单击按钮而不清除现有行的情况下将新行从数据库添加到 jTable

转载 作者:行者123 更新时间:2023-11-28 23:09:39 25 4
gpt4 key购买 nike

如何在不清除 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 作为上面代码中的表?

最佳答案

处理 ResultSet 中的每一行数据并创建一个 Vector 和 use this method将数据插入表模型。您正在创建新的表模型并将其设置在表上,带有数据的旧模型将丢失。

在评论中提出以下要求后:

这是一种方法。

Vector<Vector<String>> data=new Vector<>();
//Fill this Vector above with the initial data

Vector<String> columns=new Vector<String>();
//Fill this with column names

DefaultTableModel tableModel=new DefaultTableModel(data, columns);
JTable table=new JTable(tableModel);
//Display the table as you like

... //Query the database and get the ResultSet (let's call it rs)

while(rs.next){

Vector<String> newRow=new Vector<>();

//Get the data from the resultset and fill this new row

tableModel.addRow(newRow);

}//while closing

关于java - 如何在单击按钮而不清除现有行的情况下将新行从数据库添加到 jTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46321203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com