jdbcTemplate:事务

public int test(String sql) {
    int flag = -1;
    Connection cnn = null;
    PreparedStatement pstmt = null;
    try {
        conn = jdbcTemplate.getDataSource().getConnection();
        if(conn != null)
        {
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql);
            int flag = pstmt.executeUpdate();
            conn.commit();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        try {
            conn.rollback();
        } catch (SQLException e1) {
            System.out.println("rollback failed..");
            e1.printStackTrace();
        }
    } finally {
        try{
            conn.setAutoCommit(true);
            if(pstmt != null){
                pstmt.close();
            }
            if(conn != null){
                conn.close();
            }
        }catch(SQLException e){
            
        }
    }
    return flag;
}

猜你喜欢

转载自blog.csdn.net/m0_38084243/article/details/84142818
今日推荐