sql事务(Transaction)用法介绍及回滚实例
事务(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存储过程,这样就相对比较简单

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.
