SqlCommand myCommand = myConnection.CreateCommand();
SqlTransaction myTrans;
myTrans = myConnection.BeginTransaction();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, ´Description´)";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, ´Description´)";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
try
{
myTrans.Rollback();
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
SqlTransaction
最新推荐文章于 2025-11-09 01:00:13 发布
本文通过示例介绍了如何使用C#和SQL Server进行事务处理,确保数据的一致性和完整性。包括开始事务、执行SQL命令、提交事务及回滚异常情况。

7291

被折叠的 条评论
为什么被折叠?



