The following article is reproduced a master of the article, not my original, oh, I am not so powerful

Source: Internet
Author: User
Tags one table rollback
Use, examples, and considerations for C # transactions (turn)

I. Introduction to the Business
. NET Framework Developer's Guide
A transaction is an operation that sets up a group of logical units of work, although errors may occur in the system, but the transaction controls and maintains the consistency and integrity of each operation in the transaction.
For example, in a bank application that transfers funds from one account to another, one account credits a certain amount to a database table, while another account borrows the same amount into another database table. Because computers can fail due to power outages, network outages, and so on, it is possible to update rows in one table, but not to update rows in another table. If the database supports transactions, you can group database operations into a transaction to prevent inconsistencies in the database due to these events. If a point in the transaction fails, all updates can be rolled back to the state before the transaction started. If no failure occurs, the update is completed by committing the transaction with the completion status.
In Ado.net, you can use Connection and Transaction objects to control transactions. You can use Connection.begintransaction to start a local transaction. Once a transaction is started, you can use the Transaction property of the Command object to enlist the command in that transaction. You can then use the Transaction object to commit or roll back modifications made in the data source, depending on the success or failure of the transactional component.
You can also use Connection.EnlistDistributedTransaction to enlist in existing distributed transactions. Registering in an existing distributed transaction ensures that code modifications to the data source are committed or rolled back when the entire distributed transaction is committed or rolled back.
The following example creates a OleDbConnection and a oledbtransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.

public void Runoledbtransaction (string myconnstring)
{
OleDbConnection myconnection = new OleDbConnection ( myConnString);
Myconnection.open ();
OleDbCommand mycommand = Myconnection.createcommand ();
OleDbTransaction Mytrans;

//Start a local transaction
Mytrans = Myconnection.begintransaction (isolationlevel.readcommitted);
Assign transaction object for a pending the local transaction
Mycommand.connection = myconnection;
Mycommand.transaction = Mytrans;
Try
{
myCommand.CommandText =/"Insert into Region (RegionID, RegionDescription) VALUES (./' description/') )/";
Mycommand.executenonquery ();
myCommand.CommandText =/"Insert into Region (RegionID, RegionDescription) VALUES (A/' description/')/";
Mycommand.executenonquery ();
Mytrans.commit ();
Console.WriteLine (/"Both records are written to database./");
}
catch (Exception e)
{
Try
{
Mytrans.rollback ();
}
catch (OleDbException ex)
{
if (mytrans.connection!= null)
{
Console.WriteLine (/"An exception of type /"+ ex." GetType () +
/"is encountered while attempting to roll back the transaction./");
}
}

Console.WriteLine (/"An exception of type/" + e.gettype () +
/"is encountered while inserting the data./");
Console.WriteLine (/"Neither record is written to database./");
}
Finally
{
Myconnection.close ();
}
}

Oledbtransaction.commit Method
commits a database transaction.
Public virtual void Commit (); The
Oledbtransaction.rollback method
rolls back the transaction from a pending state.
Public virtual void Rollback ();
Oledbconnection.begintransaction method
To start the database transaction.
Public oledbtransaction BeginTransaction (); The
starts a database transaction with the current IsolationLevel value.
Public oledbtransaction BeginTransaction (IsolationLevel);
IsolationLevel enumeration? The
Specifies the transaction lockout behavior of a connection. When a transaction is executed, the. NET Framework data Provider uses the IsolationLevel value. IsolationLevel remains in effect until you make an explicit change, but you can change it at any time. The new value is used at execution time, not at analysis time. If changes are made during a transaction, the expected behavior of the server is to apply the new locking level to all remaining statements.
IsolationLevel member ReadCommitted
maintains a shared lock while reading data to avoid dirty reads, but can change data before the transaction ends, resulting in unreadable read or phantom data. The
Oledbconnection.createcommand method
Creates and returns a OleDbCommand object associated with OleDbConnection.
Public OleDbCommand CreateCommand (); The
Oledbcommand.connection property
Gets or sets the OleDbConnection used by this instance of OleDbCommand.
Public OleDbConnection Connection {get; set;}


How to be in. NET implementation Transaction (1)

How to be in. NET to implement the transaction mechanism. There are usually 2 ways to write directly to SQL, using Ado.net implementations. Here is a brief introduction:
Method 1: Write directly to SQL
Using BEGIN TRANS, COMMIT TRANS, ROLLBACK TRANS implementation:
For example
BEGIN TRANS
DECLARE @orderDetailsError int, @productError int
DELETE from/' Order details/' WHERE productid=42
SELECT @orderDetailsError = @ @ERROR
DELETE from the products WHERE productid=42
SELECT @productError = @ @ERROR
IF @orderDetailsError = 0 and @productError = 0
COMMIT TRANS
ELSE
ROLLBACK TRANS
This is a simpler approach, and you can check out the relevant SQL Server Help

Method 2: Using the Ado.net implementation, the advantage of this approach is that you can manage transactions in the middle tier, and of course you can choose to implement them at the data layer.
The SqlConnection and OleDbConnection objects have a BeginTransaction method that can return SqlTransaction or OleDbTransaction objects. And this object has a Commit and Rollback method to manage the transaction, the specific examples are as follows:

Cnnorthwind.open ()
Dim trans as SqlTransaction = Cnnorthwind.begintransaction ()
Dim Cmdel as New SqlCommand ()
Cmdel.connection = Cnnorthwind
Cmdel.transaction = trans

Try
Cmdel.commandtext = _
/"DELETE [order Details] WHERE ProductID = 42/"
Cmdel.executenonquery ()
Cmdel.commandtext =/"DELETE products WHERE ProductID = 42/"
Cmdel.executenonquery ()
Trans.commit ()

Catch XCP as Exception
Trans. Rollback ()
Finally
Cnnorthwind.close ()
End Try

Ok, the example above can achieve the same effect as Method 1.

Concurrency issues:

If there are no locks and multiple users access a database at the same time, problems may occur when their transactions use the same data at the same time. Concurrency issues include missing or overwriting updates, unacknowledged dependencies (dirty reads), inconsistent parsing (not repeating), and phantom reading. But how to avoid the problem of dirty reading when reading data.

Second, the transaction instance
using (sqltransaction trans = conn. BeginTransaction ())
{
Try
{
Looping through the insertion of information
for (int count = 0; count < applyinfo.length count + +)
{
declaring parameters and assigning values
sqlparameter[] Parms =
{Database.makeinparam (/"@Stu_ID/", System.data.sqldbtype.varchar,11,applyinfocount]. STUID),
database.makeinparam/"@Bank_Name/", System.data.sqldbtype.varchar,50,applyinfo[count]. Bankname), database.makeinparam/"@Apply_Loan_Money/", System.data.sqldbtype.money,8,applyinfo[count]. Applyloanmoney), Database.makeinparam (/"@Apply_Loan_Year/", System.data.sqldbtype.varchar,20,applyinfo[count]. applyloanyear), database.makeinparam/"@Apply_Year/", System.data.sqldbtype.char,6,applyinfo[count]. Applyyear), Database.makeinparam (/"@Apply_Length/", System.data.sqldbtype.int,4,applyinfo[count]. Applylength), Database.makeinparam (/"@Apply_Pass/", System.data.sqldbtype.char,1,applyinfo[count]. Applypass),
Database.makeinparam (/"@Apply_Remark/", System.data.sqldbtype.varchar,100,applyinfo[count]. Applyremark)
};
Perform new actions
Sqlhelper.executenonquery (trans,commandtype.storedprocedure,/"applyinfo_create/", parms);
}
No error occurred, commit transaction
Trans.commit ();
return true;
}
catch (Exception ex)
{
Roll back if an error occurs
Trans. Rollback ();
Throw ex;
}
}
Iv. Matters of note
The definition of a transaction must be committed after the connection has been opened, before closing
Transactions must be used to add transactions to the SqlCommand.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.