-1
我創建了一個存儲過程,它在NewOrder表中插入一個新訂單,並且還用OrderedProduct表的新信息更新OrderedProduct表命令。我正在使用@@IDENTITY
獲取OrderedProduct表的OrderID。使用插入查詢的輸出參數作爲另一個插入查詢的輸入參數在java中的同一個存儲過程中
我的問題是,我將如何從Java調用此存儲過程? 這就是我想到目前爲止
public static void addNewOrderToDB(ArrayList<Product> list){
Connection connection = null;
CallableStatement statement = null;
float orderValue = 0;
//calculate orderValue
for(Product p : list){
orderValue = orderValue + (p.getPrice() * p.getQty());
}
System.out.println(orderValue);
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection(url);
statement = connection.prepareCall("{ ? = CALL sp_insert_new_order(?,?,?,?)}");
statement.setFloat(3, orderValue);
statement.registerOutParameter(1, Types.INTEGER);
//statement.execute();
int uniqueID = statement.getInt(1);
System.out.println(uniqueID);
for(Product p : list){
statement.setInt(1, p.getProductId());
statement.setInt(2,uniqueID);
statement.setInt(3, p.getQty());
statement.setFloat(4, p.getPrice());
}
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally{
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
}
}
是否有任何其他方式做到這一點?
按照您的建議,要獲取我的新訂單的ID,我應該分別執行2個查詢。 – laura
對不起,我沒有看到輸出參數。我將編輯回答 –
以使用'statement.registerOutParameter(1,Types.INTEGER);'我必須調用'statement.execute();'可以使用如下輸出參數:'int uniqueID = statement。 getInt(1); (產品p:list){ \t { \t \t statement.setInt(1,p.getProductId()); \t \t statement.setInt(2,uniqueID); \t \t statement.setInt(3,p.getQty()); \t \t statement.setFloat(4,p.getPrice()); } \t}或至少這是我從你的建議中得到的結果 – laura