gpt4 book ai didi

java - 如何将新值插入两个相关表中?

转载 作者:行者123 更新时间:2023-12-02 07:29:40 25 4
gpt4 key购买 nike

我有一个用java编写的商店程序和一个用access制作的数据库。我的数据库中已经有 2 个表,即客户表和产品表。

我想添加一个订单表,其中它的主键是一个自动编号和一个 order_line 表来完成这个应用程序。我想要这样的 table ..

customer(cust_id, name, ....)
orders(order_no, cust_id, date_purchased,...)
order_line(order_no, product_id, ...)
products(product_id, product_name, price,....)

当客户购买产品时,我可以将新值插入到订单表中。我不清楚的是我如何在 order_line 表中也插入,因为我在 access 中创建的 order_no 是 autonumber 类型。

我是否需要先创建一条 select 语句来获取 order_no 值,然后将其放入 order_line 表中的 order_no 中?或者我只需将其放入一个查询中。

谁有这方面的经验?如有任何建议,我们将不胜感激。

最佳答案

插入订单和 order_line 表应该在单个事务中发生。这样做时,如果您使用普通 JDBC 将记录插入订单表,则可以 register the order_no as an OUT parameter在你的CallableStatement并在执行语句后获取值,并用于设置 order_line 记录上的 order_no 属性。

 // begin transaction
connection.setAutoCommit(false);

CallableStatement cs = connection.prepareCall(INSERT_STMT_INTO_ORDERS_TABLE);
cs.registerOutParameter(1, Types.INT);
int updateCount = cs.execute();
// Check the update count.
long orderNo = cs.getInt(1);

// CallableStatement csLine for inserting into order_line table
// for (OrderLine line: orderLines) {
// Set the orderNo in line.
// set paramters on csLine.
// csLine.addBatch();
// }
// run the batch and verify update counts
connection.commit();

// connection.rollback() on error.

关于java - 如何将新值插入两个相关表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com