using (SqlConnection SQL = new SqlConnection("data source=.;Initial Catalog=test;User ID=test;Password=1234"))
{
CommittableTransaction ct = new CommittableTransaction();
SQL.Open();
SQL.EnlistTransaction(ct);
using (SqlCommand sqlcom = new SqlCommand())
{
try
{
sqlcom.Connection = SQL;
sqlcom.CommandText = strSQL;
sqlcom.ExecuteNonQuery();
for (int i = 0; i < 1000; i++)
{
sqlcom.CommandText = string.Format("insert into [dbo].[TestTB] (A,B,C,D,E,F,H) values ('A{0}','A{1}','A{2}','A{3}','A{4}','A{5}',{6})", i, i + 1, i + 2, i + 3, i + 4, i + 9, i);
sqlcom.ExecuteNonQuery();
}
ct.Commit();
}
catch (Exception ex)
{
ct.Rollback();
}
}
}
首先先宣告明確交易的CommittableTransaction物件
1
CommittableTransaction ct = new CommittableTransaction();
using (TransactionScope ts = new TransactionScope())
{
using (SqlConnection SQL = new SqlConnection("data source=.;Initial Catalog=test;User ID=test;Password=1234"))
{
SQL.Open();
using (SqlCommand sqlcom = new SqlCommand())
{
try
{
sqlcom.Connection = SQL;
sqlcom.CommandText = strSQL;
sqlcom.ExecuteNonQuery();
for (int i = 0; i < 1000; i++)
{
sqlcom.CommandText = string.Format("insert into [dbo].[TestTB] (A,B,C,D,E,F,H) values ('A{0}','A{1}','A{2}','A{3}','A{4}','A{5}',{6})", i, i + 1, i + 2, i + 3, i + 4, i + 9, i);