小编典典

单击按钮时如何在不清除现有行的情况下从数据库向jTable添加新行

java

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


阅读 200

收藏
2020-11-30

共1个答案

小编典典

处理ResultSet中的每一行数据并创建一个Vector,然后使用此方法将数据插入表模型中。您正在创建新的表模型并将其设置在表上,带有数据的旧模型将丢失。

在以下要求后发表评论:

这是做到这一点的一种方法。

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
2020-11-30