2012-10-26 48 views
0

我有一個商店程序在java和一個數據庫訪問。我的數據庫中已經有2個表格,分別是customers表格和products表格。如何將新值插入兩個相關的表中?

我想添加一個訂單表,其中主鍵是一個自動編號和一個order_line表來完成這個應用程序。我想要這樣的桌子..

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表,因爲我在訪問中創建的order_no是類型自動編號。

我會首先創建一個select語句,讓order_no值將其置於order_no的order_line表中嗎?或者我只需要把它放在一個查詢中。

有這方面經驗的人嗎?任何建議表示讚賞。

+1

獲得從訂單表中的順序自動編號與@@身份 – Fionnuala

回答

1

插入到orders和order_line表中應該發生在單個事務中。這樣做時,如果您使用普通JDBC將記錄插入到訂單表中,則可以在CallableStatement中使用register the order_no as an OUT parameter,並在執行語句後獲取該值,並使用該值設置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. 
+0

我意識到,我仍然不知道很多的事情JDBC,感謝這個答案:) – Katherine

1

JDBC-way(如果你喜歡數據庫獨立性),就是使用getGeneratedKeys()語句的方法。

使用setAutoCommit(false),然後使用選項Statement.RETURN_GENERATED_KEYS(例如對於PreparedStatement)執行第一個查詢。

然後使用getGeneratedKeys()方法來檢索鍵(注:參考的列名,爲精確的執行和返回的列的數量取決於驅動程序實現

有了這樣的檢索鍵執行第二條語句。

最後,commit()

相關問題