Adding a row with columns that have sequenced primary and foreign key JDBC

后端 未结 2 1775
醉话见心
醉话见心 2020-12-22 12:10

My program has an add item and finish transaction option. The FinishTransaction class asks the user to input the customer\'s information, meth

2条回答
  •  佛祖请我去吃肉
    2020-12-22 12:37

    I'm pretty sure that this sql insert statement is incorrect.

    String sql3 = "INSERT INTO TRANSACTION " + 
                            "VALUES(TransNumSeq.NEXTVAL,  CustNumSeq.NEXTVAL, ?, ?)";
    

    You're inserting a record into TRANSACTION and trying to advance the sequence on CUSTOMER (CustNumSeq.NEXTVAL) . You should try to use

    //when inserting into CUSTOMER 
    pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
    pstmt.execute();//make the insert
    //and then simply grab the key
    ResultSet rs = stmt.getGeneratedKeys();
    if (rs.next()) 
    id = rs.getObject(1);
    

    Note that not every JDBC driver supports returning generated keys so you may have to use one additional select to fetch the last generated key.

    And finally, you will have to change this part to reflect the changes made above

    String sql3 = "INSERT INTO TRANSACTION " + 
                            "VALUES(TransNumSeq.NEXTVAL, ?, ?, ?, ?, ?)";
    pstmt3 = conn.prepareStatement(sql3);
    pstmt3.setInt(1, id);
    pstmt3.setInt(2, payment);
    pstmt3.setString(3, payment_desc);
    pstmt3.setInt(4, creditCard);
    pstmt3.setInt(5, change);
    

提交回复
热议问题