【发布时间】:2013-12-29 04:32:15
【问题描述】:
我创建了一个存储过程,它在 NewOrder 表中插入一个新订单,并使用订单的新信息更新 OrderedProduct 表。我正在使用@@IDENTITY 获取 OrderedProduct 表的 OrderID。
create proc sp_insert_new_order(
@oValue float,
@newID int OUTPUT,
@productID int,
@price float,
@qty int)
as
begin
insert into NewOrder values(GETDATE(),@oValue)
set @newID = @@IDENTITY
insert into OrderedProduct values(@productID,@newID,@qty,@price)
end
我的问题是如何从 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());
}
}
}
}
还有其他方法吗?
【问题讨论】:
标签: java mysql sql sql-server stored-procedures