Transactions : Transaction « Database ADO.net « Visual C++ .NET

Home
Visual C++ .NET
1.2D
2.Class
3.Collections
4.Data Type
5.Database ADO.net
6.Delegate
7.Development
8.File Directory
9.Function
10.Generics
11.GUI Form
12.Language Basics
13.Network
14.Reflection
15.Security
16.Statement
17.Structure
18.Thread
19.XML
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Visual C++ .NET » Database ADO.net » Transaction 
Transactions
 
#include "stdafx.h"
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Configuration;

void main(){
    String ^Name = "Doors";

    SqlConnection  ^connection = gcnew SqlConnection();
    SqlTransaction ^transaction;

    connection->ConnectionString = "SQLConnection";

    try{
       connection->Open();
       SqlCommand ^cmd = gcnew SqlCommand();

       transaction = connection->BeginTransaction(IsolationLevel::Serializable, "AuthorTransaction");

       cmd->Connection  = connection;
       cmd->Transaction = transaction;

       cmd->CommandType = CommandType::StoredProcedure;
       cmd->CommandText = "InsertAuthor";

       cmd->Parameters->Add(gcnew SqlParameter("@LastName", SqlDbType::Char,32));
       cmd->Parameters->Add(gcnew SqlParameter("@FirstName",SqlDbType::Char,32));

       cmd->Parameters["@LastName"]->Value  = "Dope";
       cmd->Parameters["@FirstName"]->Value = "John";

       int affected = cmd->ExecuteNonQuery();
       if (affected <= 0)
           throw gcnew Exception("Insert Failed");
       Console::WriteLine("Insert - {0} rows are affected", affected);

       cmd->CommandType = CommandType::Text;
       cmd->CommandText = "UPDATE Authors SET LastName = 'Doe' WHERE LastName = 'Dope'";

       affected = cmd->ExecuteNonQuery();
       if (affected <= 0)
           throw gcnew Exception("Insert Failed");
       Console::WriteLine("Update - {0} rows are affected", affected);

       cmd->CommandType = CommandType::Text;
       cmd->CommandText = "DELETE FROM Authors WHERE LastName = 'Does'";

       affected = cmd->ExecuteNonQuery();
       if (affected <= 0)
           throw gcnew Exception("Insert Failed");
       Console::WriteLine("Delete - {0} rows are affected", affected);

       transaction->Commit();
    }
    catch (Exception ^e)
    {
        transaction->Rollback("AuthorTransaction");
        Console::WriteLine("Transaction Not completed");
        Console::WriteLine("SQL error occurred: {0}", e->Message);
    }
    finally
    {
        connection->Close();
    }
}

   
  
Related examples in the same category
1.Using Transactions
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.