sql server 数据库的事务
一.定义
事务就是被绑定在一起作为一个逻辑工作单元的SQL语句组,如果任何一个语句操作失败那么整个操作就被失败,进而回滚到操作前状态,或者是上个节点。为了确保要么执行,要么不执行,就可以使用事务。要将一组语句作为事务考虑,就需要通过ACID测试,即原子性,一致性,隔离性和持久性。
二.什么情况用事务
当数据库需要处理操作量大、复杂度高的数据的时候需要用到事务。用事务是为了保证数据库的完整性,保证成批的 SQL 语句要么全部执行,要么全部不执行。
三.使用举例
--转账
go
--定义一个变量,记录错误数
declare @error_nums int set @error_nums=0
--开始事务
begin transaction tran_change
begin try
update Customer set Remain=Remain-200 where id=1
set @error_nums=@error_nums+@@ERROR
update Customer set Remain=Remain+200 where id=2
set @error_nums=@error_nums+@@ERROR
end try
begin catch
set @error_nums=@error_nums+1
print '错误异常:'+convert(varchar,error_number())+',错误消息'+error_message()
end catch
if(@error_nums>0)--表示前面有错
rollback transaction tran_change--回滚事务
else
commit transaction tran_change--执行事务
select * from Customer
四.扩展(转账功能)
1.创建存储过程
--创建存储过程
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 '错误异常:'+convert(varchar,error_number())+',错误消息'+error_message()
end catch
if(@error_nums>0)--表示前面有错
rollback transaction tran_change--回滚事务
else
commit transaction tran_change--执行事务
exec cp_changeAccount 1,2,200
select * from Customer
2.用MVC模式实现
①.控制器代码
public class CustomerController : Controller
{
EnRole_DBEntities ed = new EnRole_DBEntities();
// GET: Customer
//显示客户信息
public ActionResult Index()
{
var customer = ed.Customers.ToList();
return View(customer);
}
//转账的方法
[HttpPost]
public ActionResult ChangeRemain(int idOut,int idIn,decimal Remain)
{
//转账
//跳转到方法index
try
{
ed.cp_changeAccount(idOut, idIn, Remain);
}
catch (Exception)
{
return Content("错误");
}
return RedirectToAction("index");
}
②.视图
@{
ViewBag.Title = "Index";
}
@using ChangeAccount.Models
@model List<Customer>
<h2>转账</h2>
<form action="/Customer/ChangeRemain" method="post">
<div class="form-group">
<label for="idOut">请输入打款人编号</label>
<input type="text" class="form-control" name="idOut" />
</div>
<div class="form-group">
<label for="idIn">请输入收款人编号</label>
<input type="text" class="form-control" name="idIn" />
</div>
<div class="form-group">
<label for="Remain">请输入转账金额</label>
<input type="text" class="form-control" name="Remain" />
</div>
<input type="submit" value="转账" class="btn btn-primary" />
<table class="table table-bordered">
<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>