日期:2014-05-18  浏览次数:20634 次

SQL 事务处理
我写了一个函数,   想要把删除和插入联合成一个事务,   要么全执行,   要么都不执行?
不知道   怎么写?


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;

}

------解决方案--------------------
给个例子:
***************************************

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) { }
}
}
}