Home Database Mysql Tutorial Sql Server数据库事务介绍(二)

Sql Server数据库事务介绍(二)

Jun 07, 2016 pm 03:23 PM
server sql main affairs introduce database

本节主要介绍Sql语句,SqlTransaction和TransactionScope这三种使用事务的方法。 本节的所有例子都在sql server 2008和vs 2008环境下运行通过,如果没有sql server2008,那么使用sql server 2005也一样,但是sql se rver 2000上是无法运行通过的,因为某些sq

      本节主要介绍Sql语句,SqlTransaction和TransactionScope这三种使用事务的方法。

      本节的所有例子都在sql server 2008和vs 2008环境下运行通过,如果没有sql server2008,那么使用sql server 2005也一样,但是sql se rver 2000上是无法运行通过的,因为某些sql语句在2000中不支持。请大家注意这点。

       请先执行下面的脚本,在本机的数据库实例中建立测试数据库,以方便运行例子。

 

      首先介绍利用Sql语句来使用事务。Sql Server2005/2008提供了begin tran,commit tran和rollback tran三个语句来显示的使用事务。begin tran表示事务开始,commit tran表示事务提交,rollback tran表示事务回滚。具体代码如下:

      代码中的begin try和begin catch是捕获异常时使用的,只在sql server2005/2008中支持,sql server 2000上不支持这个语句。在begin try 和 end try之间的代码运行时如果发生异常,则程序会跳转到begin catch和end catch中执行相关的rollback tran回滚操作。在begin tran和commit tran之间就是一个事务,insert和update必须同时成功,否则就同时失败。RAISERROR 语句的意思是抛出一个异常,只在sql server2005/2008中支持,sql server 2000上不支持这个语句。

      执行上面的代码,我们会发现,插入和更新同时都成功了。把RAISERROR的注释去掉后,再执行,我们会发现,插入和更新都回滚了。因为RAISERROR抛出异常后,没有执行到commit tran,而是直接执行begin catch里面的rollback tran回滚语句了。

 

      下面介绍SqlTransaction的使用方法。SqlTransaction是System.Data.SqlClient命名空间下的一个事务类,主要方法有Commit()和Rollback()两个函数,更多方法和属性请参考MSDN。具体代码如下:

上面的代码显示了SqlTransaction类的基本使用方法。首先使用SqlConnection建立连接后,sqlConn.BeginTransaction()表示事务的开始,在执行一些基本操作后(代码是执行一个insert和一个update)后,执行sqlTrans.Commit();表示事务提交,这时候,刚才insert和update的数据在数据库才能被使用。如果把throw new Exception("test exception.the transaction must rollback");这句的注释去掉,我们会发现,程序没有执行提交,而是直接执行了catch中的Rollback(),进行了回滚。那么刚才的insert和update一起被回滚。

 

       最后看一下TransactionScope的基本用法。TransactionScope继承IDisposable接口,所以一般在using中使用。具体代码如下:



在using中定义了一个TransactionScope,相当于定义了一个事务范围即这个事务作用域为using内。程序执行了两个动作,一个insert,一个update,最后执行了scope.Complete();相当于提交事务。如果把scope.Complete();注释掉,我们会发现insert和update都被回滚了,因为在using作用域内,如果没有提交命令,那么scope在销毁时,会自动回滚所有的操作

 

      以上就是三种事务的基本使用方法,在此基础之上,还可以引申出更多的问题,比如嵌套事务,三种方法的混合使用等问题。在此就不一一列举了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

See all articles