首页 > 解决方案 > 返回重复项

问题描述

我尝试使用此代码将我的数据插入到我的数据库中,但我不断重复,我似乎无法弄清楚如何修复它。我是 Java 和 MySQL 的新手,因此非常感谢任何帮助或指导。

以下是我的代码

ApproveButton = new JButton("Approve");
        ApproveButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
        ApproveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            

            try{

                int rows=table.getRowCount();
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo", "root123", "root12345");
                
             PreparedStatement upd = connection.prepareStatement("INSERT INTO approvedsales(productname, quantity, price, total, date) VALUES (?, ?,?,?,? )");

                
                for(int row = 0; row<rows; row++)
                {
                    String productname = (String)table.getValueAt(row, 0);
                    String quantity = (String)table.getValueAt(row, 1);
                    String price = (String)table.getValueAt(row, 2);
                    String total = (String)table.getValueAt(row, 3);
                    String date = (String)table.getValueAt(row, 4);
                    upd.setString(1, productname);
                    upd.setString(2, quantity);
                    upd.setString(3, price);
                    upd.setString(4, total);
                    upd.setString(5, date);

                    upd.addBatch();
                }
                upd.executeBatch();
                int x = upd.executeUpdate();
                if (x == 0) {
                    
                JOptionPane.showMessageDialog(ApproveButton, "This is alredy exist");
            } else {
                JOptionPane.showMessageDialog(ApproveButton,
                    "Data are successfully stored");
            }}
                catch(Exception exception){
                    exception.printStackTrace();
                }
        }});
        ApproveButton.setBounds(129, 204, 89, 23);
        contentPane.add(ApproveButton);

我在数据库中的表,所有列都是 varchar(255),没有唯一键和主键

productname  quantity  price  total  date
biscuits        1       1      1      7th Sept 2020


标签: javamysql

解决方案


只使用Statement#executeBatch,而不是 executeUpdate。

int[] xs = upd.executeBatch();
if (IntStream.of(xs).min().orElse(1) == 0) { ...

通过执行executeUpdate,SQL 会被执行两次。

当然,产品表的列定义中的 PRIMARY KEY 会很好。

此外,MySQL 可以将 INSERT 与 UPDATE 选项结合起来,REPLACE 是 - 我相信 - 这个名字。


推荐阅读