📄 orderservice.java
字号:
package com.hygj.service;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
public class OrderService {
private Connection conn=null;
private PreparedStatement pt=null;
private CallableStatement call=null;
private int orderId;
/**
* 实现生成订单,同时获得订单编号
*/
public int getOrderId(int userId){
conn=com.hygj.util.ConnUtil.getConn();
try {
call=conn.prepareCall("{call proc_getIdByNew(?,?)}");
call.setInt(1,userId);
call.registerOutParameter(2,java.sql.Types.INTEGER);
//执行过程
call.execute();
//执行完成后再获得结果
orderId=call.getInt(2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
close();
}
return orderId;
}
/**
* 向订单明细表中添加信息
*/
public int addOrderDetails(int userId,Hashtable car){
//先获得订单编号
orderId=this.getOrderId(userId);
conn=com.hygj.util.ConnUtil.getConn();
try {
//设置手动提交
conn.setAutoCommit(false);
pt=conn.prepareStatement("insert into orderDetails values(?,?,?)");
//获得要添加的具体信息
Enumeration keys=car.keys();
while(keys.hasMoreElements()){
//获得具体的商品信息
String productId=(String)keys.nextElement();
String shuliang=(String)car.get(productId);
//为pt进行参数赋值
pt.setInt(1,orderId);
pt.setInt(2,Integer.parseInt(productId));
pt.setInt(3,Integer.parseInt(shuliang));
//把生成好的语句放到批处理中
pt.addBatch();
}
//执行批处理
pt.executeBatch();
//提交事务
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//把手动提交改回自动提交
try {
conn.setAutoCommit(true);
close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return orderId;
}
public void close(){
try{
if(pt!=null){
pt.close();
}
if(call!=null){
call.close();
}
if(conn!=null){
conn.close();
}
}catch(Exception e){
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -