您的位置:程序门 -> java -> web 开发



sql 事务处理


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


sql 事务处理
发表于:2007-05-20 19:47:13 楼主
我写了一个函数,   想要把删除和插入联合成一个事务,   要么全执行,   要么都不执行?
不知道   怎么写?


public   boolean   addbatch(int   roleid,   int   permissionid[])   {

try   {

//   先删除所有的数据,   然后再插入所有的数据
ssql   =   "delete   from   rolespermissions   where   roleid= "   +   roleid;
stmt   =   conn.createstatement();
rs   =   stmt.EXECutequery(ssql);

preparedstatement   stmt   =   conn
.preparestatement( "insert   into   rolespermissions   values(?,?,?) ");

for   (int   i   =   0;   i   <   permissionid.length;   i++)   {
stmt.setint(2,   roleid);
stmt.setint(1,   permissionid[i]);
stmt.addbatch();
}
int[]   counts=stmt.EXECutebatch();

}   catch   (sqlexception   e)   {
//   todo   auto-generated   catch   block
e.printstacktrace();
}
return   flag;

}
发表于:2007-05-20 20:16:421楼 得分:0
给个例子:
***************************************

public   class   orderhandler   extends   httpservlet   {

    public   void   dopost(httpservletrequest   req,   httpservletresponse   res)
                                                                throws   servletexception,   ioexception   {
        res.setcontenttype( "text/plain ");
        printwriter   out   =   res.getwriter();

        connection   con   =   null;
        try   {
            class.forname( "sun.jdbc.odbc.jdbcodbcdriver ");
            con   =   drivermanager.getconnection( "jdbc:odbc:ordersdb ",   "user ",   "passwd ");

            //   turn   on   transactions
            con.setautocommit(false);

            statement   stmt   =   con.createstatement();
            stmt.EXECuteupdate(
                "update   inventory   set   stock   =   (stock   -   10)   where   productid   =   7 ");
            stmt.EXECuteupdate(
                "update   shipping   set   shipped   =   (shipped   +   10)   where   productid   =   7 ");

            chargecard();     //   method   doesn 't   actually   exist...

            con.commit();
            out.println( "order   successful!     thanks   for   your   business! ");
        }
        catch   (exception   e)   {
            //   any   error   is   grounds   for   rollback
            try   {
                con.rollback();
            }
            catch   (sqlexception   ignored)   {   }
            out.println( "order   failed.   please   contact   technical   support. ");
        }
        finally   {
            //   clean   up.
            try   {
                if   (con   !=   null)   con.close();
            }
            catch   (sqlexception   ignored)   {   }
        }
    }
}


快速检索

最新资讯
热门点击