学习笔记--在vs中使用事务

什么是事务

事务就是被绑定在一起作为一个逻辑工作单元的SQL语句组,如果任何一个语句操作失败那么整个操作就被失败,进而回滚到操作前状态,或者是上个节点。为了确保要么执行,要么不执行,就可以使用事务。要将一组语句作为事务考虑,就需要通过ACID测试,即原子性,一致性,隔离性和持久性。

表字段
在这里插入图片描述

表内数据
在这里插入图片描述

如何在vs中使用

先在SQL中创建一个存储过程
并在其中创建事务

--创建存储过程
create proc cp_changeAccount
(
@idOut int,
@idIn int,
@Remain decimal(18,2)
)
as
--定义一个变量,记录错误数
declare @error_nums int
set @error_nums=0
--开始事务
begin transaction tran_change
begin try
update Customer set Remain=Remain-@Remain
where id=@idOut
set @error_nums=@error_nums+@@ERROR
update Customer set Remain=Remain+@Remain
where id=@idIn
set @error_nums=@error_nums+@@ERROR
end try
begin catch
set  @error_nums=@error_nums+1
print '错误异常:' +error_number()+'错误消息'+error_message()
end catch
if(@error_nums>0) --表示前面有错
rollback transaction tran_change --回滚事务
else
commit transaction tran_change

下面是vs代码

创建一个 .net 应用开发程序
创建名为 changeAccount 的项目
项目内控制器名为 CustomerController
控制器代码

using System.Linq;
using System.Web.Mvc;
using changeAccount.Models;
namespace changeAccount.Controllers
{
    public class CustomerController : Controller
    {
        EnRoleEntities db = new EnRoleEntities();
        // GET: Customer
        public ActionResult Index()
        {
            var cunstomer = db.Customers.ToList();
            return View(cunstomer);
        }
        [HttpPost]
        public ActionResult ChangeRemain(int idOut, int idIn, decimal Remain)
        {
            //转账
            var a = db.cp_changeAccount(idOut, idIn, Remain);
            //跳转
            return RedirectToAction("index");
        }
    }
}

index页面代码

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="/customer/ChangeRemain" method="post">
    <p>
        <a asp-action="Create"></a>
    </p>
    打款人
    <input type="text" name="idOut" value="" />
    收款人
    <input type="text" name="idIn" value="" />
    打款金额
    <input type="text" name="Remain" value="" />
    <input type="submit" />

    <table class="table">
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>金额</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.ID</td>
                    <td>
                        @item.Name
                    </td>
                    <td>
                        @item.Remain
                    </td>                
                </tr>
            }
        </tbody>
    </table>
</form>

运行项目后页面显示如下效果
在这里插入图片描述
提交前
在这里插入图片描述
提交后
在这里插入图片描述
事务调用完成

猜你喜欢

转载自blog.csdn.net/weixin_47975226/article/details/106378357