将更新表a和表b的操作放在一个事务中,出错就rollback

解决方案 »

  1.   

    我一般都这样做:怎么同时更新2张表
    public boolean addProduct(String productname,String kindid ,String model,String weight,
                                       String price,String explain,String picurlid ,String companyid)
    {
    ResultSet rs=null;
    boolean bolRet = false;
    List co_List = new ArrayList();
    String sql = " INSERT INTO CO_PRODUCT("
    + " productNAME," //1.名称
    + " kindID," //2.类别ID
    + " model," //3.规格
    + " weight," //4.重量
    + " price," //5.价格
    + " explain," //6.说明
    + " REGSITERTIME,"      //7.注册时间
    + " PICURLID," //8.图片ID
    + " COMPANYID," //9.对应企业ID
    + " ISAVAILABILITY )" //10是否生效
    + " VALUES(?,?,?,?,?,?,?,?,?,?)";
    DatabaseTool tool = DatabaseTool.getInstance(sql);
             //获取制定格式的当前时间
             java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
             java.util.Date currentTime_1 = new java.util.Date();
             String now = (String) formatter.format(currentTime_1);
    try
    {
                tool.setString(1,productname);
                tool.setString(2,kindid);
                tool.setString(3,model);
                tool.setString(4,weight);
                tool.setString(5,price);
                tool.setString(6,explain);
                tool.setString(7,now);
                tool.setString(8,picurlid);
                tool.setString(9,companyid);
                tool.setInt(10,0);
    tool.executeUpdate();
    bolRet = true; } catch (SQLException e)
    {
                bolRet = false;
                System.out.println("Error in news_newsInsert " + e);
    } finally {
                tool.close(); //关闭连接
                tool = null;
                return bolRet;
    }
    }
      

  2.   

    把操作数据库的代码放入一个TRY块中,操作前把自动提交设置为不自动提交,然后操作完数据库后一次提交.如果操作出现操作会抛出SQLExecption,然后CATCH到这个异常并把数据库操作回滚,并且关闭数据库连接.
      

  3.   

    hjw_929(老人)说的对,
    给一段伪代码:connection1.setAutoCommit(false)
    try{
       boolean ok1=  SQLupdate1...
       boolean ok2 = SQLupdate2...
       if( ok1 && ok2 ) {
          connection1.commit();
       } else {
          connection1.rollback();
    }catch(SQLException se){
       System.out.println( se );
       connection1.rollback();
       connection1.close();
    }
    ...