1. 程式人生 > >dbUtils事務處理

dbUtils事務處理

控制層
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String from = request.getParameter("from");
        String to 
= request.getParameter("to"); double money =Double.parseDouble( request.getParameter("money")); MoneyService ms = new MoneyService(); Boolean flag = ms.trans(from,to,money); if(flag) { response.getWriter().println("轉賬成功"); }else { response.getWriter().println(
"轉賬失敗"); } } 業務層 public Boolean trans(String from, String to, double money) { MoneyDao md = new MoneyDao(); Connection conn = c3p0Util.getConn(); try { conn.setAutoCommit(false); int a = md.from(from,money,conn);
int b = md.to(to,money,conn); if(a*b>0) { DbUtils.commitAndCloseQuietly(conn); return true; } } catch (Exception e) { e.printStackTrace(); DbUtils.rollbackAndCloseQuietly(conn); } return false; } 持久層 public class MoneyDao { public int from(String from, double money,Connection conn) throws Exception { String sql = "update account set money=money-? where name=?"; QueryRunner qr = new QueryRunner(); int i = qr.update(conn, sql, money,from); return i; } public int to(String to, double money,Connection conn) throws Exception { String sql = "update account set money=money+? where name=?"; QueryRunner qr = new QueryRunner(); int i = qr.update(conn, sql, money,to); return i; } }