What is the transaction mechanism and what is the use of the transaction? I will not explain it here,
This blog post addresses how to use the transaction mechanism to solve some basic problems,
This is a simple transaction processing problem. Here we will briefly introduce three transaction mechanisms,
The first method is to use System. Data. SqlClient. SqlTransaction,
The second method is to use System. Transactions. TransactionScope,
The third method is implemented using System. Transactions. CommittableTransaction,
Among them, the first one is a traditional practice,
The latter two types are introduced in. Net Framework 2.0,
The first estimation is that there is no need to explain it more, because it continues in ADO. NET,
The latter two types are somewhat different from the first one,
You will see it in the Demo below,
In ADO. NET, you can either use a transaction or not use a transaction,
Therefore, when using transactions, you must tell the application,
The SqlConnection you are currently using uses the transaction mechanism,
For example:
One practice when using SqlTransaction:
SqlConnection sqlCon = new SqlConnection (conStr)
SqlTransaction sqlTran = sqlCon. BeginTransaction ();
In this way, you will be notified of the application,
The defined transaction is enabled from the SqlConnection.
HoweverSystem. Transactions. TransactionScopeA little special,
When using it, you do not need to display which SqlConnection is declared to use the transaction mechanism,
However, this does not mean that the application does not need to be notified when this method is used,
Essentially,System. Transactions. TransactionScopeThis method is also called implicit transaction,
As long as your SqlConnection is inSystem. Transactions. TransactionScopeWithin the scope,
This SqlConnection will be automatically enabled,
System. Transactions. TransactionScopeThis transaction mechanism,
For example,
You use
Using (System. Transactions. TransactionScope tranScope =
New TransactionScope ())
{
.........
.........
}
All sqlconnections in this using statement block will be automatically used.
System. Transactions. TransactionScopeThis transaction mechanism,
For the third method, the statement must be displayed,
To specify a SqlConnection to enable the transaction mechanism.
The above is a simple description of the three transaction mechanisms,
Next, let's look at a Demo,
This Demo is used for parsing,
Code-Behind
Using System;
Using System. Transactions;
Using System. Data;
Using System. Data. SqlClient;
Using System. Configuration;
Namespace CSharpLanguage
{
Public partial class Demo _ 11: System. Web. UI. Page
{
Private string conStr = "";
Protected void Page_Load (object sender, EventArgs e)
{
ConStr = ConfigurationManager.
ConnectionStrings ["Demo"]. ConnectionString;
}
// Use SqlTransaction to complete the transaction
Protected void btnSqlTransaction_Click (object sender, EventArgs e)
{
// This SQL statement can be successfully executed.
String sqlStr1 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"34534", "XiaoZhen", "12 ");
// This SQL statement can fail to be executed.
String sqlStr2 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"978867", "BaoBeiMe", "male ");
String [] sqlStr = new string [2];
SqlStr [0] = sqlStr1;
SqlStr [1] = sqlStr2;
Using (SqlConnection sqlCon = new SqlConnection (conStr ))
{
SqlCon. Open ();
SqlTransaction sqlTran = sqlCon. BeginTransaction ();
Using (SqlCommand sqlCom = sqlCon. CreateCommand ())
{
SqlCom. CommandType = CommandType. Text;
SqlCom. Transaction = sqlTran;
Try
{
For (int I = 0; I <sqlStr. Length; I ++)
{
SqlCom. CommandText = sqlStr [I];
SqlCom. ExecuteNonQuery ();
}
// All SQL statements can be submitted after execution is successful.
SqlTran. Commit ();
LblMsg. Text = "execution successful ";
}
Catch (Exception exc)
{
SqlTran. Rollback ();
LblMsg. Text = "transaction failed" + exc. Message. ToString ();
}
}
}
}
// Use System. Transaction. TransactionScope to complete the Transaction
Protected void btnTransactionScope_Click (object sender, EventArgs e)
{
// This SQL statement can be successfully executed.
String sqlStr1 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"345390674", "XiaoZhen", "12 ");
// This SQL statement can fail to be executed.
String sqlStr2 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"978876867", "BaoBeiMe", "male ");
String [] sqlStr = new string [2];
SqlStr [0] = sqlStr1;
SqlStr [1] = sqlStr2;
// TransactionScope is an implicit transaction mechanism.
// Write TransactionScope in this using statement block,
// All sqlconnections in this statement block are automatically
// Associate the TransactionScope.
// This transaction mechanism is used for all sqlconnections in this using statement block.
Using (System. Transactions. TransactionScope tranScope =
New TransactionScope ())
{
Using (SqlConnection sqlCon = new SqlConnection (conStr ))
{
SqlCon. Open ();
Using (SqlCommand sqlCom = sqlCon. CreateCommand ())
{
Try
{
SqlCom. CommandType = CommandType. Text;
For (int I = 0; I <sqlStr. Length; I ++)
{
SqlCom. CommandText = sqlStr [I];
SqlCom. ExecuteNonQuery ();
}
// Submit after all SQL statements are successfully executed
// Because only when all SQL statements are successfully executed,
// This transaction will complete the operation,
// As long as one execution fails,
// All will fail and there is no need to roll back
TranScope. Complete ();
LblMsg. Text = "execution successful ";
}
Catch (Exception exc)
{
LblMsg. Text = "transaction failed" + exc. Message. ToString ();
}
}
}
}
}
// Use System. Transaction. CommittableTransaction to complete the Transaction
Protected void btnCommittableTransaction_Click (object sender, EventArgs e)
{
// This SQL statement can be successfully executed.
String sqlStr1 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"34341534", "XiaoZhen", "12 ");
// This SQL statement can fail to be executed.
String sqlStr2 = String. Format ("insert into" +
"Student (ID card number, Student name, gender)" +
"VALUES ('{0}', '{1}', '{2 }')",
"3232434", "BaoBeiMe", "male ");
String [] sqlStr = new string [2];
SqlStr [0] = sqlStr1;
SqlStr [1] = sqlStr2;
Using (System. Transactions. CommittableTransaction commitTran =
New CommittableTransaction ())
{
Using (SqlConnection sqlCon = new SqlConnection (conStr ))
{
SqlCon. Open ();
// This CommittableTransaction is different from TransactionScope.
// It will not be automatically associated with all sqlconnections in the using statement Block
// Therefore, you must use the EnlistTransaction of SqlConnection to manually
// Bind the SqlConnetion to the transaction mechanism
// So that this SqlConnection can use transactions
SqlCon. EnlistTransaction (commitTran );
Using (SqlCommand sqlCom = sqlCon. CreateCommand ())
{
SqlCom. CommandType = CommandType. Text;
Try
{
For (int I = 0; I <sqlStr. Length; I ++)
{
SqlCom. CommandText = sqlStr [I];
SqlCom. ExecuteNonQuery ();
}
CommitTran. Commit ();
LblMsg. Text = "execution successful ";
}
Catch (Exception exc)
{
LblMsg. Text = "transaction failed" + exc. Message. ToString ();
CommitTran. Rollback ();
}
}
}
}
}
}
}
HTML
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Br/>
<Asp: Button ID = "btnSqlTransaction" runat = "server"
Text = "use SqlTransaction to implement transactions"
OnClick = "btnSqlTransaction_Click"/>
& Nbsp; <br/>
<Br/>
<Asp: Button ID = "btnTransactionScope" runat = "server"
Text = "use TransactionScope to implement transactions"
OnClick = "btnTransactionScope_Click"/>
<Br/>
<Br/>
<Asp: Button ID = "btnCommittableTransaction" runat = "server"
Text = "use CommittableTransaction to implement transactions"
OnClick = "btnCommittableTransaction_Click"/>
<Br/>
<Br/>
<Asp: Label ID = "lblMsg" runat = "server" Text = ""> </asp: Label>
</Div>
</Form>
</Body>
</Html>
Then, let's take a look at the results,
Because I define two SQL statements for each button event,
One failed to execute, and the other succeeded,
If the transaction mechanism is not enabled, one transaction will be successfully executed for a long time,
A transaction fails to be executed. After the transaction mechanism is enabled,
All operations will fail in the past two days,
All the above events will fail to be executed.
The above three buttons are the same result no matter which one is pressed -- failed
In this way, a simple transaction mechanism is implemented.
Pay attention to the Code section and understand the meaning of the comment.
2010-2-02