事务(Transaction)是并发控制的单位,是用户定义的一个操作序列。这些操作要么都做,要么都不做,是一个不可分割的工作单位。通过事务,SQL Server能将逻辑相关的一组操作绑定在一起,以便服务器保持数据的完整性
当对多个表进行更新的时候,某条执行失败。为了保持数据的完整性,需要使用事务回滚。
显示设置事务
代码如下 | 复制代码 |
begin try begin transaction insert into shiwu (asd) values ('aasdasda'); commit transaction end try begin catch select ERROR_NUMBER() as errornumber rollback transaction end catch |
隐式设置事务
代码如下 | 复制代码 |
set implicit_transactions on; -- 启动隐式事务 |
显示事务以下语句不能使用,隐式事务可以
代码如下 | 复制代码 |
alter database; |
显示事务可以嵌套使用
代码如下 | 复制代码 |
--创建存储过程 create procedure qiantaoProc @asd nchar(10) as begin begin try begin transaction innerTrans save transaction savepoint --创建事务保存点 insert into shiwu (asd) values (@asd); commit transaction innerTrans end try begin catch rollback transaction savepoint --回滚到保存点 commit transaction innerTrans end catch end go begin transaction outrans exec qiantaoProc 'asdasd'; rollback transaction outrans |
事务嵌套,回滚外层事务时,如果嵌套内的事务已经回滚过则会有异常。此时需要使用事务保存点。如下实例
SQL事务回滚
指定当 Transact-SQL 语句产生运行时错误时,Microsoft® SQL Server™ 是否自动回滚当前事务
方案一:
代码如下 | 复制代码 |
SET XACT_ABORT ON--如果产生错误自动回滚 GO BEGIN TRAN INSERT INTO A VALUES (4) INSERT INTO B VALUES (5) COMMIT TRAN |
也可以使用_ConnectionPtr 对象的方法: BeginTrans、CommitTrans、RollbackTrans,使用该系列函数判断并回滚。一旦调用了 BeginTrans 方法, 在调用 CommitTrans 或 RollbackTrans 结束事务之前, 将不再立即提交所作的任何更改。
方案二
代码如下 | 复制代码 |
BEGIN TRANSACTION INSERT INTO A values (4) ----- 该表含有触发器,UPDATE其他表 IF @@error 0 --发生错误 BEGIN ROLLBACK TRANSACTION END ELSE BEGIN COMMIT TRANSACTION END |
sql事务结合asp.net两种用法
在sql server+ .net 开发环境下,有两种方法能够完成事务的操作,保持数据库的数据完整性;一个就是用/42850.htm target=_blank >sql存储过程,另一个就是在ADO.NET中一种简单的事务处理;现在通过一个典型的银行转账的例子来说明一下这两个例子的用法我们先来看看sql存储过程是如何来完成事务的操作的:首先创建一个表:
代码如下 | 复制代码 |
create database aaaa --创建一个表,包含用户的帐号和钱数gouse aaaacreate table bb( ID int not null primary key, --帐号 moneys money --转账金额)insert into bb values ('1','2000') --插入两条数据insert into bb values ('2','3000')用这个表创建一个存储过程: @toID int, --接收转账的账户 @fromID int , --转出自己的账户 @momeys money --转账的金额 as begin tran --开始执行事务
update bb set moneys=moneys-@momeys where ID=@fromID -执行的第一个操作,转账出钱,减去转出的金额 update bb set moneys=moneys+@momeys where ID=@toID --执行第二个操作,接受转账的金额,增加
if @@error0 --判断如果两条语句有任何一条出现错误 begin rollback tran –开始执行事务的回滚,恢复的转账开始之前状态 return 0 end go
else --如何两条都执行成功 begin commit tran 执行这个事务的操作 return 1 end go |
接下来看看.net 是如何调用这个存储过程的:
代码如下 | 复制代码 |
protected void Button1_Click(object sender, EventArgs e) { SqlConnection con =new SqlConnection(@"Data Source=.SQLEXPRESS;database=aaaa;uid=sa;pwd=jcx"); //连接字符串 SqlCommand cmd = new SqlCommand("mon",con); //调用存储过程 cmd.CommandType = CommandType.StoredProcedure; con.Open(); SqlParameter prar = new SqlParameter();//传递参数 cmd.Parameters.AddWithValue("@fromID", 1); cmd.Parameters.AddWithValue("@toID", 2); cmd.Parameters.AddWithValue("@momeys",Convert.ToInt32( 1.Text) );
cmd.Parameters.Add("@return", "").Direction = ParameterDirection.ReturnValue;//获取存储过程的返回值 cmd.ExecuteNonQuery(); string value = cmd.Parameters["@return"].Value.ToString();//把返回值赋值给value if (value == "1") { Label1.Text = "添加成功"; } else { Label1.Text = "添加失败"; } } |
这个也就是在存储过程里添加事务,再来看看不在数据库写sql存储过程,ADO.NET是如何处理事务的:
代码如下 | 复制代码 |
protected void Button2_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=.SQLEXPRESS;database=aaaa;uid=sa;pwd=jcx"); con.Open(); SqlTransaction tran = con.BeginTransaction();//先实例SqlTransaction类,使用这个事务使用的是con 这个连接,使用BeginTransaction这个方法来开始执行这个事务 SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.Transaction = tran; try { //在try{} 块里执行sqlcommand命令, cmd.CommandText = "update bb set moneys=moneys-'" + Convert.ToInt32(TextBox1.Text) + "' where ID='1'"; cmd.ExecuteNonQuery(); cmd.CommandText = "update bb set moneys=moneys+' aa ' where ID='2'"; cmd.ExecuteNonQuery(); tran.Commit();//如果两个sql命令都执行成功,则执行commit这个方法,执行这些操作
Label1.Text = "添加成功"; } catch { Label1.Text = "添加失败"; tran.Rollback();//如何执行不成功,发生异常,则执行rollback方法,回滚到事务操作开始之前; }
} |
这就是两个事务不同用法的简单例子,ADO.NET 事务处理的方法看起来比较简单,但是他要使用同一个连接来执行这些操作,要是同时使用几个数据库来用一个事务执行,这样就比较繁琐,但是要是用sql存储过程,这样就相对比较简单

This article explores optimizing MySQL memory usage in Docker. It discusses monitoring techniques (Docker stats, Performance Schema, external tools) and configuration strategies. These include Docker memory limits, swapping, and cgroups, alongside

This article addresses MySQL's "unable to open shared library" error. The issue stems from MySQL's inability to locate necessary shared libraries (.so/.dll files). Solutions involve verifying library installation via the system's package m

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

This article compares installing MySQL on Linux directly versus using Podman containers, with/without phpMyAdmin. It details installation steps for each method, emphasizing Podman's advantages in isolation, portability, and reproducibility, but also

This article provides a comprehensive overview of SQLite, a self-contained, serverless relational database. It details SQLite's advantages (simplicity, portability, ease of use) and disadvantages (concurrency limitations, scalability challenges). C

This guide demonstrates installing and managing multiple MySQL versions on macOS using Homebrew. It emphasizes using Homebrew to isolate installations, preventing conflicts. The article details installation, starting/stopping services, and best pra

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
