java - getValueAt() 将数据库中的条目加倍

标签 java mysql jdbc

我编写了一个小程序,它使用JTable(在本例中为t1)并实现ListSelectionListener,因此通过单击一行,其中的数据将被放入数据库中(我使用mysql并通过JDBC连接)。

//  t1 is a JTable
t1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
t1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

    @Override
    public void valueChanged(ListSelectionEvent e) {

           int row = t1.getSelectedRow();

           try {
               String sql = "INSERT INTO xxx (x1, x2, x3) VALUES(?,?,?)";

               PreparedStatement pst = conn.prepareStatement(sql);

               int col1 = (int)t1.getValueAt(row, 0);
               int col2 = (int)t1.getValueAt(row, 1);
               int col3 = (int)t1.getValueAt(row, 2);

               pst.setLong(1, col1);
               pst.setLong(2, col2);
               pst.setLong(3, col3);

               pst.addBatch();

               pst.executeBatch();
        } 

           catch (SQLException e1) {

            e1.printStackTrace();
        }
    }
});

除了每行被放入数据库两次之外,一切正常。例如,如果我选择第三行,我会在数据库中获得两次。在我看来,按下鼠标时它会生成一个条目,释放时会生成一个条目,当我使用键盘箭头时它不会出现。谁能帮我吗?

最佳答案

请使用以下逻辑

ListSelectionModel selectionModel = table.getSelectionModel();
    selectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if ( e.getValueIsAdjusting() ){
                return;
             }
             if (e.getSource() == table.getSelectionModel() && 
                 table.getRowSelectionAllowed() ) {
               int selected = table.getSelectedRow();
               System.out.println("Column 1 : " + table.getValueAt(selected, 0));
               System.out.println("Column 2 : " + table.getValueAt(selected, 1));
               System.out.println("Column 3 : " + table.getValueAt(selected, 2));
             }
        }
    });

我看了这篇文章java-listselectionlistener-interface-with-keyboard

关于java - getValueAt() 将数据库中的条目加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236798/

相关文章:

java - 我如何指向随 secret 钥(firebase 用户 ID)

php - 在 PHP 中如何获取包含 PREPARE 和 EXECUTE 的 SQL 查询返回的行?

php - 如何在 Laravel 中执行此操作,使用 join 进行子查询

java - 连接 mysql 服务器失败

mysql - 从 clojure 连接到 mysql 服务器

java - Spring Boot Rest 中自连接到 JSON

具有 200 个变量的 Java POJO 设计

java - 缺少多个 IF 的 return 语句

php - 数据库设计和图像文件系统管理?

java - JCombobox 根据 true/false 调整文本