What is the object SqlConnection.BeginTransaction useful for
When I connect to database by ADO.NET. As for SqlConnection object, it has a func开发者_开发问答tion: BeginTransaction with 3 overloads. I don't know how to use it and what's its function for?
A transaction ensures a block of work operates in an ACID way - all or nothing.
The optional name is useful for DBAs when tracking long-running transactions. In TSQL directly the names are more important, for save-points etc - but in the OO world you have an object for that.
The isolation level determines how ACID it is. Serializable is the most pure, but has more overhead costs in terms of additional locks (key-range locks, etc).
Typical usage would be:
using (SqlTransaction tran = conn.BeginTransaction())
{
try
{
/* work here, assigning "tran" onto
* any commands */
tran.Commit();
}
catch
{
tran.Rollback();
throw;
}
}
In many ways, it is simpler to use TransactionScope
- this creates an ambient transaction, into which commands enlist automatically. It can also span multiple dbs etc courtesy of DTC:
using(TransactionScope tran = new TransactionScope())
{
/* work here; no need to assign tran to anything */
tran.Complete();
}
A transaction is used to guarantee that a group of actions (sql statements) are either all carried out (a commit) or none are carried out (a rollback).
A typical use is where updates to two or more tables must all succeed (or all fail).
精彩评论