在C#.NET中如何创建一个数据库操作事务!谢谢

gj121 2005-01-15 09:25:33
如题!
...全文
318 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
nga96 2005-01-15
  • 打赏
  • 举报
回复
对,楼上的都说了,就这样干就是。直接启动一个事务
机器人 2005-01-15
  • 打赏
  • 举报
回复
通过Connection对象调用 BeginTransaction 来创建 Transaction 对象。对Transaction 对象执行与该事务关联的所有后续操作(例如提交或中止该事务)。
Ivony 2005-01-15
  • 打赏
  • 举报
回复
IDbConnection.BeginTransaction()
yiyi0518 2005-01-15
  • 打赏
  • 举报
回复
数据库采用Sql Server的话比较简单,有相应的控件~~~

其他的话就只好写一个数据库访问类进行操作了~~~

个人观点,有不足之处请各位指正~~
DimVar 2005-01-15
  • 打赏
  • 举报
回复
贴一段供你参考:
SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;Trusted_Connection=yes;database=northwind");
SqlCommand myCommand = new SqlCommand();
SqlTransaction myTrans;

// Open the connection.
myConnection.Open();

// Assign the connection property.
myCommand.Connection = myConnection;

// Begin the transaction.
myTrans = myConnection.BeginTransaction();

// Assign transaction object for a pending local transaction
myCommand.Transaction = myTrans;

try
{
// Restore database to near it's original condition so sample will work correctly.
myCommand.CommandText = "DELETE FROM Region WHERE (RegionID = 100) OR (RegionID = 101)";
myCommand.ExecuteNonQuery();

// Insert the first record.
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
myCommand.ExecuteNonQuery();

// Insert the second record.
myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'MidEastern')";
myCommand.ExecuteNonQuery();

myTrans.Commit();
Console.WriteLine("Both Records are written to the database!");
}
catch(Exception e)
{
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record is written to the database!");
}
finally
{
myConnection.Close();
}

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧