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

标签 java sql ms-access jdbc

我有一个用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/

相关文章:

mysql - 结合 UNION 和 LEAST 的查询构造

ms-access - "Operation not supported in transactions"在 Access 中复制/粘贴记录时

java - 如何让Selenium等待页面上的元素被替换(java)

java - 通过逻辑复制将 Postgres 数据库更改转换为 Java 应用程序

java - 为什么我们不需要实现Serialized来序列化为xml

sql - Foxpro:通过vfpoledb检查表是否存在

mysql - sql计算我没有解决

sql-server - 我可以从 Microsoft Access 调用 SQL Server 的用户定义函数吗

excel - 如何将参数发送到 Microsoft Access 查询,以便我可以将 Access 参数查询导入到 Excel?

Java JDBC : establish a persistent connection which lasts days