SQL中的事务

 SQL中的事务

事务:
begin transaction       开始事务
commit transaction 提交事务
rollboack transaction 回滚事务

set implicit_ransaction on    隐式事务
update customer set nickname-'nicky'
where customerId=10
这样这条语句不会改变数据,必须在最后加上,commit transaction 才会提交上述事务.
因为我们指明使用隐式事务,所以每一条语句都会当成是一个事务,所以要commit transaction才能提交.


事务完整性:违反事务完整性的问题有3类: 脏读 (dirty read)、不可重复读(nonrepeatable read)、幻影行(phantom rows)
解决这3个问题,需要在事务之间使用不同的完整性或者隔离级别。

脏读:一个事务读取了另一个事务尚未提交的更新,就叫做脏读。
例:

set transaction isolation level read committed   --设置事务不允许脏读,可重复读,可幻影行
--transaction 1    打开查询分析器,建立一个连接,运行以下命令
use northwind
begin transaction
update customers
set CompanyName='transaction1'
where CustomerId='ALFKI'

      
commit transaction     --这个命令暂不运行,不让这个事务提交


--transaction 2   在建立一个连接,运行以下命令
use northwind
set transaction isolation level read uncommitted   --设置事务可以脏读
select * from customers
where customerid='ALFKI'

这里能够成功读取到事务1还没有提交更改的数据,此时己经发生了脏读

这里运行以下命令
set transaction isolation level read committed   --设置事务不可以脏读
select * from customers
where customerid='ALFKI'

这时出现延时现象,因为我们设的是不可脏读。 此时将连接1 运行 commit transaction  发现连接2马上显示出了数据。

 


不可重复读:如果事务二能够看到事务一所提交的数据更新,就意味着出了不可重复读型事务缺陷。
例:
在以上建立的连接2中,运行以下命令
--transaction 2
set transaction isolation level repeatable read   --设置事务不可重复读
begin transaction
select * from customers
where customerid='ALFKI'


select * from customers       标注:A
where customerid='ALFKI'
commit transaction

 


在以上建立的连接1中,运行以下命令,发现连接1出现延时现象,说明事务二无法更改同一条数据,在时在连接2中运行标注:A以下的命令,
因为连接1无法更改所以不会出现重复读现象。 标注A:以下命令完成后,连接1更改数据成功。
--transaction 1
begin transaction
update customers
set CompanyName='non-repeatable111'
where CustomerId='ALFKI'
commit transaction

 

幻影行:当一个事务的select语句返回的结果受到另一个事务的影响而发生改变的现象叫做幻影行。
不做测试了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值