简体   繁体   中英

MySQL inserting data Twice in Java

I am trying to insert data to a table (order_details) from another table (cart) . When I am executing this, It insert data twice in database. I can't figure why it happens. Can anybody help me? Thanks in advance.

CartDAO

public boolean insertCart(String username)
    {
        try
        {
            sql = "INSERT INTO order_details (username, product_code, product_name, qty, product_price, product_pic, order_status)"
                  +"SELECT username, product_code, product_name, qty, product_price, product_pic, order_status FROM cart WHERE username = ? AND order_status = 1";
            con = DbConnection.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1, username);
            pst.executeUpdate();
            DbConnection.close();
            return true;
        }catch(ClassNotFoundException | SQLException ex)
        {
            Logger.getLogger(CartDAO.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

CartWS

public boolean insertOrderDetails(String username)
    {
        CartDAO dao = new CartDAO();
        return dao.insertCart(username);
    }

Add some log statement in your code,

there may be 2 possible reasons for duplicate insertion issue

(1) Your method "insertCart" are calling 2 times from the code. if you add System.out.println() OR some log statement inside insertCart method ... you will be able to find out.

OR

(2) Print your SELECT query before insertion query, like below

System.out.println(SELECT username, product_code, product_name, qty, product_price, product_pic, order_status FROM cart WHERE username = ? AND order_status = 1) 

// donot forget to replace ? with appproriate value

The number of records you are getting from the SELECT statement must be same what you are inserting into the table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM