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

妖精的绣舞 提交于 2019-11-29 18:07:15
dsp_user

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);

1) I don't see that you are maintaining any transaction in your code.
2) In case, if there is any error in the last insert, you'll not be able to see the data in 3rd table. Check your logs for any exception while making insert into third table.
3) Problem that looks quite obvious to me is:

"INSERT INTO TRANSACTION " + 
                            "VALUES(TransNumSeq.NEXTVAL, **CustNumSeq.NEXTVAL**, ?, ?, ?, ?)"

...You are calling the sequence second time, it will have different cust_no than what you have inserted in the first statement.
4) In case, you have defined the cust_num as foreign key in transaction table, the code should break. Because this cust_num doesn't exist in customer table yet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!