在JTable中添加行,并自动增加最后一行id

时间:2012-08-17 03:44:34

标签: java swing jdbc jtable auto-increment

我的问题是:我如何实现一个“添加行”按钮,该按钮创建一个新的JTable行(从SQLite数据库中获取数据),其中包含最后一行id的自动增量++。 id列已经自动增加了数据,现在我知道创建一个所有字段为空的新行(没有最新行的增量++)。 请有人帮忙吗?

private void cmd_newrowActionPerformed(java.awt.event.ActionEvent evt) {
     ((DefaultTableModel) PrimaryTable.getModel()).addRow(new Vector());
}

我想要的是什么:

==================
id  |  data      |
==================
1   | some_data  |
2   | some_data  |
3   | some_data  |
==================


After I press addRow button:

==================
id  |  data      |
==================
1   | some_data  |
2   | some_data  |
3   | some_data  |
4   | blank      |        /// blank row data with an autoincrement of the row id
==================

更新

好的,现在我知道如何在数据库中插入新行,但我不知道如何更新JXTable。因此,它运行的波纹管代码,以及重新启动应用程序后更新的新空白行。有人可以帮帮我吗?

private void cmd_newrowActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        String sql = "Insert into RDSSPrimaryTable (sample_no,mineral_name,chemical_formula,main_peaks,other_peaks,reference,link,comments,spectrum) values (?,?,?,?,?,?,?,?,?)";

        pst = conn.prepareStatement(sql);
        // no pst.setString for id - it takes automatically

        pst.setString(1, txt_sample_pt.getText());
        pst.setString(2, txt_mineral_pt.getText());
        pst.setString(3, txt_chemical_pt.getText());
        pst.setString(4, txt_main_pt.getText());
        pst.setString(5, txt_other_pt.getText());
        pst.setString(6, txt_reference_pt.getText());
        pst.setString(7, txt_link_pt.getText());
        pst.setString(8, txt_comments_pt.getText());
        pst.setBytes(9, person_image);

        JOptionPane.showMessageDialog(null, "Inserted");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);

    }

    ((DefaultTableModel) PrimaryTable.getModel()).fireTableDataChanged(); // I tried this method even if the DefaultTableModel fire table automatically.

    PrimaryTable.repaint(); //tried also repaint, revalidate - nothing happens

}

1 个答案:

答案 0 :(得分:0)

使用以下代码在数据库中创建序列

CREATE SEQUENCE sample_number
  START WITH     1
  INCREMENT BY   1;

然后在您的代码中进行以下更改:

String sql = "Insert into RDSSPrimaryTable (sample_no,mineral_name,chemical_formula,main_peaks,other_peaks,reference,link,comments,spectrum) values (sample_number.nextval(),?,?,?,?,?,?,?,?)";

pst = conn.prepareStatement(sql);

pst.setString(1, txt_mineral_pt.getText());
pst.setString(2, txt_chemical_pt.getText());
pst.setString(3, txt_main_pt.getText());
pst.setString(4, txt_other_pt.getText());
pst.setString(5, txt_reference_pt.getText());
pst.setString(6, txt_link_pt.getText());
pst.setString(7, txt_comments_pt.getText());
pst.setBytes(8, person_image);