设为首页 收藏本站

MCBANG

 找回密码
 立即注册

QQ登录

只需一步,快速开始

快捷导航
搜索
查看: 12813|回复: 0

[转载] 数据库操作之事务处理

[复制链接]
发表于 2012-12-8 16:10:28 |显示全部楼层
cpp代码
  1. #include "stdafx.h"
  2. using namespace System;
  3. using namespace System::Data;
  4. using namespace System::Data::OleDb;

  5. ref struct MyEventHandler
  6. {
  7. static void RowUpdated(Object^ sender, OleDbRowUpdatedEventArgs^ e)
  8. {
  9. if ( e->Status == UpdateStatus::ErrorsOccurred )
  10. throw "Row update failed!";
  11. }
  12. };

  13. void main()
  14. {
  15. OleDbConnection^ myConnection = nullptr;
  16. OleDbTransaction^ myTransaction = nullptr;

  17. try
  18. {
  19. myConnection = gcnew OleDbConnection(
  20. "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Music.mdb");
  21. myConnection->Open();

  22. OleDbDataAdapter^ dataAdapter = gcnew OleDbDataAdapter(
  23. "SELECT * FROM Music", myConnection);
  24. OleDbCommandBuilder^ commandBuilder = gcnew OleDbCommandBuilder(dataAdapter);
  25. dataAdapter->UpdateCommand = commandBuilder->GetUpdateCommand();

  26. dataAdapter->RowUpdated += gcnew OleDbRowUpdatedEventHandler(MyEventHandler::RowUpdated);

  27. DataSet^ myDataSet = gcnew DataSet();
  28. dataAdapter->MissingSchemaAction = MissingSchemaAction::AddWithKey;
  29. dataAdapter->Fill(myDataSet);

  30. myTransaction = myConnection->BeginTransaction();

  31. DataTable^ myTable = myDataSet->Tables[0];

  32. DataRow^ row = myTable->Rows->Find("Automatic");
  33. if ( row != nullptr )
  34. row["Title"] = "Automatic (Dance Mix)";

  35. row = myTable->Rows->Find("EnTrance");
  36. if ( row != nullptr )
  37. row["GenreName"] = "Trance";

  38. dataAdapter->Update(myDataSet);
  39. myTransaction->Commit();
  40. }
  41. catch(Exception^ e)
  42. {
  43. Console::WriteLine(e->Message);
  44. if ( myTransaction != nullptr )
  45. {
  46. myTransaction->Rollback();
  47. Console::WriteLine("Transaction rolled back.");
  48. }
  49. }
  50. finally
  51. {
  52. myConnection->Close();
  53. }
  54. }
复制代码
  大家好,我是Timiky,一个学习中的程序猿,,喜欢程序的关注我哦!
欢迎来到网络尖刀新生代网络安全综合媒体! 请记住我们的网址 Www.Mcbang.Com [官方Q群:55420062]
您需要登录后才可以回帖 登录 | 立即注册

Archiver|知娱 ( 京ICP备14006288号-3  

GMT+8, 2020-4-2 03:29 , Processed in 0.152350 second(s), 31 queries .

请勿发布违反中华人民共和国法律法规的言论
郑重声明:本站会员观点不代表【网络尖刀】论坛官方立场。

Copyright© 2006-2016 IjianDao.Com All rights reserved. 知娱 版权所有

回顶部