public boolean insertEmail(Email email)
{
conn=new Conn().getconn();
String sql="insert into Email values(?,?,?,?,?)";
try {
pt=conn.prepareStatement(sql);
                        pt.setString(1, email.getAddresser());
pt.setString(2, email.getAddressee());
pt.setString(3, email.getTitle());
pt.setString(4, email.getContent());
pt.setDate(5, email.getSendtime());
a=pt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
this.ClossAll();
}
if(a>0)
return true;
else
return false;
}public boolean deleteEmail(int id)
{
conn=new Conn().getconn();
String sql="delete * from Email wher id=?";
try {
pt=conn.prepareStatement(sql);
pt.setInt(1, id);
a=pt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if(a>0)
return true;
else
return false;
}
请问怎么给上面这两个方法添加事物?

解决方案 »

  1.   

    伪代码:
    ..
    connection.setAutoCommit(false);
    ..
    try {
    ........
    connection.commit()
    ...
    } catch (E) {
    ...
    connection.rollback()
    ...
    } finally {
    ...
    }
      

  2.   

    public int addOrderDetrail(int userId, Hashtable car) {
    // 先添加定单表
    orderId = new com.hygj.service.OrderService().addOrder(userId);
    conn = ConnUtil.getConn();
    try {
    // 再做定单明细
    pt = conn.prepareStatement("insert into orderDetails values(?,?,?)");
    // 把自动提交事务更改成手动提交
    conn.setAutoCommit(false);
    // 遍历购物车,获得商品编号和数量
    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));
    // 把生成sql语句添加到批处理中
    pt.addBatch();
    }
    // 一次性执行批处理
    pt.executeBatch();
    // 进行提交处理
    conn.commit();
    // 把提交改成自动提交
    conn.setAutoCommit(true);
    } catch (SQLException e) {
    // 回滚事务
    try {
    conn.rollback();
    } catch (SQLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    } finally { closeConn();
    } return orderId;
    }那这种事物与上边的事物有什么区别么