原生sql和django的事务控制

def test(request):
    with connections['default'].cursor() as c:
        try:
            with transaction.atomic(using='default'):
                team_sql='insert into permission_team VALUES (%s,%s,%s)'

                per_sql="insert into permission_permission VALUES (%s,%s,%s,%s)"
                c.execute(team_sql,[11,'一2组',4])
                team_result=c.fetchall()
                c.execute(per_sql,['ddd','啊哈哈','test','用户管理'])
                # per_result=c.fetchone()
        except Exception as e:
            return render(request,'error/raise_error.html',{'e':e})
    return HttpResponse(6666)


# 注意如果,直接使用装饰器@transaction.atomic(),因为try语句,transaction无法捕捉到异常,因此只能写在函数中
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from on_mod.models import Permission,Role
from django.db import connections,transaction
# @transaction.atomic()
def a(request):
    cursor = connections['default'].cursor()
    # Role.objects.filter(name=u'管理').delete()
    sql = """update account_user set username ='666' WHERE id =4"""
    sql_team = """update  permission_team set name='测试啊' WHERE id=2"""
    try:
        with transaction.atomic(using='default'):
            cursor.execute(sql)
            raise KeyboardInterrupt
            cursor.execute(sql_team)

    except KeyboardInterrupt as e :
        print(6666)
    return HttpResponse(666)

参考:https://blog.csdn.net/qq_23934063/article/details/72809279

posted @ 2018-04-25 09:44  nanaindi  阅读(655)  评论(0编辑  收藏  举报