SQL 事务处理

yyzone 2007-05-20 07: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;

}
...全文
172 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
javaboy2006 2007-05-20
  • 打赏
  • 举报
回复
给个例子:
***************************************

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

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧