当前位置:Gxlcms > mysql > NET事务隐式事务

NET事务隐式事务

时间:2021-07-01 10:21:17 帮助过:26人阅读

如需运行分布式事务,需启动 T-SQL : CreateTableTranTable ( IdINTIDENTITY(1,1)PRIMARYKEY, PriorityTINYINT-- 最大值 255 ) C# : stringsql1="INSERTINTOTranTableVALUES(1)";// 正常插入 stringsql2="INSERTINTOTranTableVALUES(256)";// 插入异常 ADO

如需运行分布式事务,香港空间,美国服务器,需启动

T-SQL

Create Table TranTable

(

Id INT IDENTITY(1,1) PRIMARY KEY,

Priority TINYINT--最大值255

)

C#

string sql1 = "INSERT INTO TranTable VALUES(1)";//正常插入

string sql2 = "INSERT INTO TranTable VALUES(256)";//插入异常

ADO.NET事务

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString))
{
conn.Open();
using (SqlTransaction tran = conn.BeginTransaction())
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Transaction = tran;
try
{
cmd.CommandText = sql1;
cmd.ExecuteNonQuery();
cmd.CommandText = sql2;
cmd.ExecuteNonQuery();
tran.Commit();
Response.Write("Ok");
}
catch (SqlException ex)
{
tran.Rollback();
Response.Write("Error:" + ex.Message);
}
}
}
conn.Close();
}

ADO.NET

分布式隐式事务(TransactionScope)

隐式事务不具有

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySqlServer"].ConnectionString))
{
using (TransactionScope ts = new TransactionScope())
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
try
{
cmd.CommandText = "insert into TranTable(Priority) values(1)";
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into TranTable(Priority) values(256)";
cmd.ExecuteNonQuery();
ts.Complete();
Response.Write("Ok");
}
catch (SqlException ex)
{
Response.Write("Error:" + ex.Message);
}
}
}
conn.Close();
}

TransactionScope没有和数据库直接关联,那是怎么实现用事务的方式执行语句的呢?

如果我们在连接字符串里面加上

分布式显示事务(CommittableTransaction)

人气教程排行