ADO.NET 수동 트랜잭션을 코딩하는 방법

다음 코드에서는 트랜잭션으로 예금 전송 작업을 보호하기 위해 SQL Server .NET Data Provider에서 제공되는 트랜잭션 지원의 장점을 활용하는 방법을 보여 줍니다. 이 작업은 동일 데이터베이스에 있는 두 계정 간에 예금을 전송합니다.

public void TransferMoney( string toAccount, string fromAccount, decimal amount )
{
  using ( SqlConnection conn = new SqlConnection(
            "server=(local);Integrated Security=SSPI;database=SimpleBank" ) )
  {
    SqlCommand cmdCredit = new SqlCommand("Credit", conn );
    cmdCredit.CommandType = CommandType.StoredProcedure;
    cmdCredit.Parameters.Add( new SqlParameter("@AccountNo", toAccount) );
    cmdCredit.Parameters.Add( new SqlParameter("@Amount", amount ));

    SqlCommand cmdDebit = new SqlCommand("Debit", conn );
    cmdDebit.CommandType = CommandType.StoredProcedure;
    cmdDebit.Parameters.Add( new SqlParameter("@AccountNo", fromAccount) );
    cmdDebit.Parameters.Add( new SqlParameter("@Amount", amount ));

    conn.Open();
    // Start a new transaction
    using ( SqlTransaction trans = conn.BeginTransaction() )
    {
      // Associate the two command objects with the same transaction
      cmdCredit.Transaction = trans;
      cmdDebit.Transaction = trans;
      try
      {
        cmdCredit.ExecuteNonQuery();
        cmdDebit.ExecuteNonQuery();
        // Both commands (credit and debit) were successful
        trans.Commit();
      }
      catch( Exception ex )
      {
        // transaction failed
        trans.Rollback();
        // log exception details . . .
        throw ex;
      }
    }
  }
}

http://msdn.microsoft.com/ko-kr/library/system.transactions.transactionscope.aspx

 

System.Transactions 인프라는 Transaction 클래스 기반의 명시적 프로그래밍 모델과 TransactionScope 클래스를 사용하는 암시적 프로그래밍 모델을 둘 다 제공합니다. 후자의 경우 인프라에서 자동으로 트랜잭션을 관리합니다.

new 문으로 TransactionScope를 인스턴스화하면 트랜잭션 관리자가 참여할 트랜잭션을 결정합니다. 결정 후에는 이 범위가 항상 해당 트랜잭션에 참여합니다. 앰비언트 트랜잭션이 있는지 여부와 생성자에 있는 TransactionScopeOption 매개 변수의 값에 따라 참여할 트랜잭션이 결정됩니다. 앰비언트 트랜잭션이란 해당 코드가 실행되는 트랜잭션입니다. Transaction 클래스의 정적 Current 속성을 호출하면 앰비언트 트랜잭션에 대한 참조를 가져올 수 있습니다. 이 매개 변수의 사용 방법에 대한 자세한 내용은 트랜잭션 범위를 사용하여 암시적 트랜잭션 구현 항목의 "트랜잭션 흐름 관리" 단원을 참조하십시오.

트랜잭션 범위(즉, TransactionScope 개체 초기화와 Dispose 메서드 호출 사이)에서 예외가 발생하지 않으면 범위가 참여하는 트랜잭션을 계속할 수 있습니다. 트랜잭션 범위에 예외가 발생하면 범위가 참여하는 트랜잭션이 롤백됩니다.

응용 프로그램이 트랜잭션에서 수행할 작업을 모두 완료하면 Complete 메서드를 한 번만 호출하여 트랜잭션 커밋이 허용됨을 트랜잭션 관리자에게 알려야 합니다. 이 메서드를 호출하지 못하면 트랜잭션이 중단됩니다.

Dispose 메서드를 호출하면 트랜잭션 범위의 끝이 표시됩니다. 이 메서드를 호출한 후에 발생하는 예외는 트랜잭션에 영향을 주지 않습니다.

범위 안의 Current 값을 수정하면 Dispose를 호출할 경우 예외가 throw됩니다. 그러나 범위 끝에서 이전 값이 복원됩니다. 또한 트랜잭션을 만든 트랜잭션 범위 안의 Current에서 Dispose를 호출하면 범위 끝에서 트랜잭션이 중단됩니다.

// This function takes arguments for 2 connection strings and commands to create a transaction
// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the
// transaction is rolled back. To test this code, you can connect to two different databases
// on the same server by altering the connection string, or to another 3rd party RDBMS by
// altering the code in the connection2 code block.
static public int CreateTransactionScope(
    string connectString1, string connectString2,
    string commandText1, string commandText2)
{
    // Initialize the return value to zero and create a StringWriter to display results.
    int returnValue = 0;
    System.IO.StringWriter writer = new System.IO.StringWriter();

    // Create the TransactionScope to execute the commands, guaranteeing
    // that both commands can commit or roll back as a single unit of work.
    using (TransactionScope scope = new TransactionScope())
    {
        using (SqlConnection connection1 = new SqlConnection(connectString1))
        {
            try
            {
                // Opening the connection automatically enlists it in the
                // TransactionScope as a lightweight transaction.
                connection1.Open();

                // Create the SqlCommand object and execute the first command.
                SqlCommand command1 = new SqlCommand(commandText1, connection1);
                returnValue = command1.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                // If you get here, this means that command1 succeeded. By nesting
                // the using block for connection2 inside that of connection1, you
                // conserve server and network resources as connection2 is opened
                // only when there is a chance that the transaction can commit.  
                using (SqlConnection connection2 = new SqlConnection(connectString2))
                    try
                    {
                        // The transaction is escalated to a full distributed
                        // transaction when connection2 is opened.
                        connection2.Open();

                        // Execute the second command in the second database.
                        returnValue = 0;
                        SqlCommand command2 = new SqlCommand(commandText2, connection2);
                        returnValue = command2.ExecuteNonQuery();
                        writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
                    }
                    catch (Exception ex)
                    {
                        // Display information that command2 failed.
                        writer.WriteLine("returnValue for command2: {0}", returnValue);
                        writer.WriteLine("Exception Message2: {0}", ex.Message);
                    }
            }
            catch (Exception ex)
            {
                // Display information that command1 failed.
                writer.WriteLine("returnValue for command1: {0}", returnValue);
                writer.WriteLine("Exception Message1: {0}", ex.Message);
            }
        }

        // The Complete method commits the transaction. If an exception has been thrown,
        // Complete is not  called and the transaction is rolled back.
        scope.Complete();
    }

    // The returnValue is greater than 0 if the transaction committed.
    if (returnValue > 0)
    {
        writer.WriteLine("Transaction was committed.");
    }
    else
    {
        // You could write additional business logic here, for example, you can notify the caller
        // by throwing a TransactionAbortedException, or logging the failure.
        writer.WriteLine("Transaction rolled back.");
    }

    // Display messages.
    Console.WriteLine(writer.ToString());

    return returnValue;

DataTable 데이터 xml로 저장하기

           private System.Data.DataTable dt = new DataTable ("number");

            dt.Columns.Add("이름");
            dt.Columns.Add("나이");
            DataRow dr;
            dr = dt.NewRow();
            dr[0] = "고재두";
            dr[1] = "ㅋㅋ";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "서태지";
            dr[1] = "몰라";

            dt.Rows.Add(dr);

//데이터가 제대로 들어왔는지 테스트하기 위해서 바인딩 해본다

this.dataGridView1.DataSource = dt;

저장

               dt.WriteXml(Application.StartupPath + @"\number.xml", true);

불러오기


                System.Data.DataTable ddd = new DataTable("number");             
                ddd.ReadXmlSchema(Application.StartupPath + @"\number.xml");
                ddd.ReadXml(Application.StartupPath + @"\number.xml");

테스트


                this.dataGridView1.DataSource = ddd;

저장된 xml

<?xml version="1.0" standalone="yes" ?>

- <DocumentElement>

- <number>

<이름>고재두</이름>

<나이>ㅋㅋ</나이>

</number>

- <number>

<이름>서태지</이름>

<나이>몰라</나이>

</number>

</DocumentElement>

끝~

[SqlDataSource] 웹 서버 컨트롤 개요

SqlDataSource 웹 서버 컨트롤 개요

SqlDataSource 컨트롤을 사용하면 웹 컨트롤을 사용하여 OLE DB와 ODBC 데이터 소스는 물론 Microsoft SQL Server와 Oracle 데이터베이스 같은 관계형 데이터베이스에 있는 데이터에 액세스할 수 있습니다. GridView, FormView 및 DetailsView 컨트롤처럼 데이터를 표시하는 다른 컨트롤과 SqlDataSource 컨트롤을 함께 사용하여 코드를 거의 사용하지 않고 ASP.NET 웹 페이지에서 데이터를 표시하거나 조작할 수 있습니다.

SqlDataSource 컨트롤을 데이터 소스에 연결

<HTML>
  <BODY>
    <FORM runat="server">
      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT LastName FROM Employees">
      </asp:SqlDataSource>
      <asp:ListBox
          id="ListBox1"
          runat="server"
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>
    </FORM>
  </BODY>
</HTML>

SqlDataSource 컨트롤을 사용하여 데이터 명령 실행

SelectCommand, UpdateCommand, DeleteCommand 및 InsertCommand라는 최대 네 개의 명령(SQL 쿼리)을 SqlDataSource 명령에 지정할 수 있습니다. 각 명령은 데이터 소스 컨트롤의 개별 속성입니다. 각 명령 속성에 대해 데이터 소스 컨트롤에서 실행할 SQL 문을 지정합니다. 저장 프로시저를 지원하는 데이터베이스에 데이터 소스 컨트롤이 연결되면 SQL 문 대신 저장 프로시저의 이름을 지정할 수 있습니다.

런타임에 제공할 값의 자리 표시자를 포함하여 매개 변수가 있는 명령을 만들 수 있습니다. 다음 예제에서는 매개 변수가 있는 SQL Select 명령을 보여 줍니다.

Select CustomerID, CompanyName From Customers Where City = @city

런타임에 명령이 매개 변수 값을 가져오는 위치(예: 다른 컨트롤, 쿼리 문자열 등)를 지정하는 매개 변수 개체를 만들 수 있습니다. 또는 프로그래밍 방식으로 매개 변수 값을 지정할 수도 있습니다. 자세한 내용은 SqlDataSource 컨트롤에 매개 변수 사용을 참조하십시오.

데이터 소스 컨트롤은 해당하는 Select, Update, Delete 또는 Insert 메서드가 호출되면 명령을 실행합니다. Select 메서드는 페이지 또는 데이터 소스 컨트롤에 바인딩된 컨트롤의 DataBind 메서드를 호출하면 자동으로 호출됩니다. 또한 데이터 소스 컨트롤에서 명령을 실행하려는 경우 네 가지 메서드 중 하나를 명시적으로 호출할 수 있습니다.

GridView와 같은 일부 컨트롤에서는 이러한 네 개의 메서드를 호출하거나 DataBind 메서드를 명시적으로 호출할 필요 없이 자동으로 메서드를 호출할 수 있습니다.

자세한 내용은 SqlDataSource 컨트롤을 사용하여 데이터 선택SqlDataSource 컨트롤을 사용하여 데이터 수정을 참조하십시오.

DataSet 또는 DataReader 개체 반환

SqlDataSource 컨트롤은 DataSet 개체 또는 ADO.NET 데이터 판독기라는 두 가지 형식으로 데이터를 반환할 수 있습니다. 데이터 소스 컨트롤의 DataSourceMode 속성을 설정하여 반환 형식을 지정할 수 있습니다. DataSet 개체에는 서버 메모리의 모든 데이터가 포함되어 있으며 데이터를 가져온 후 다양한 방법으로 조작할 수 있습니다.

데이터 판독기는 개별 레코드를 페치할 수 있는 읽기 전용 커서를 제공합니다. 일반적으로 데이터를 가져온 후 데이터를 필터링, 정렬 또는 페이징하려는 경우나 캐시를 유지 관리하려는 경우에 데이터 집합을 반환하도록 선택합니다.

이와 달리 단순히 데이터를 반환하기만 하고 페이지의 컨트롤을 사용하여 이 데이터를 표시하려는 경우에는 데이터 판독기를 사용합니다.

예를 들어 결과 목록이 읽기 전용 형식으로 표시되는 ListBox, DropDownList 또는 GridView 컨트롤에 표시할 데이터를 반환하려면 데이터 판독기를 사용하는 것이 좋습니다.

SqlDataSource.SelectCommand 속성

<HTML>
    <BODY>
        <FORM runat="server">
            <asp:DropDownList
                id="DropDownList1"
                runat="server"
                DataTextField="LastName"
                DataSourceID="SqlDataSource1" />
            <asp:SqlDataSource
                id="SqlDataSource1"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
                SelectCommandType="StoredProcedure"               
                SelectCommand="sp_lastnames">
            </asp:SqlDataSource>
            <!--
                The sp_lastnames stored procedure is
                CREATE PROCEDURE sp_lastnames AS
                   SELECT LastName FROM Employees
                GO
            -->
        </FORM>
    </BODY>
</HTML>

SqlDataSource 컨트롤에 매개 변수 사용

SELECT * FROM Employees WHERE LastName = @LastName AND FirstName = @FirstName

라는 쿼리를 실행시키고 싶을때....

명명된 매개 변수를 사용하는 경우 명령에 대한 매개 변수 컬렉션에 지정된 매개 변수의 순서는 별로 중요하지 않습니다. 그러나 SQL 명령에 사용하는 매개 변수의 이름이 연결된 컬렉션에 있는 매개 변수의 이름과 일치하도록 해야 합니다.

다음 예제에서는 System.Data.SqlClient 공급자를 사용하는 SqlDataSource 컨트롤에 대한 SQL 명령에 명명된 매개 변수를 사용하는 방법을 보여 줍니다.

<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"

SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (@LastName, @FirstName);

SELECT @EmpID = SCOPE_IDENTITY()"

UpdateCommand="UPDATE Employees SET LastName=@LastName, FirstName=@FirstName WHERE EmployeeID=@EmployeeID"

DeleteCommand="DELETE Employees WHERE EmployeeID=@EmployeeID" ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>" OnInserted="EmployeeDetailsSqlDataSource_OnInserted"

RunAt="server">

<SelectParameters>

<asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" /> </SelectParameters>

<InsertParameters>

<asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />

</InsertParameters>

</asp:sqlDataSource>

SqlDataSource 컨트롤의 필터링을 사용하도록 설정

SqlDataSource 컨트롤을 사용하면 쿼리를 다시 실행하지 않고도 쿼리 결과를 필터링(정렬 또는 선택)할 수 있습니다. SqlDataSource 컨트롤에 필터링을 추가하면 쿼리가 실행된 후 데이터베이스로 돌아가지 않고도 SqlDataSource를 통해 사용할 수 있는 데이터를 변경할 수 있습니다.

SqlDataSource 컨트롤의 필터링을 사용하도록 설정하려면

  1. 유효한 연결 문자열과 Select 문을 사용하여 SqlDataSource 컨트롤을 만듭니다. 자세한 내용은 방법: SqlDataSource 컨트롤을 사용하여 SQL Server 데이터베이스에 연결을 참조하십시오.

  2. SqlDataSource 컨트롤의 DataSourceMode 속성을 DataSet로 설정합니다.

  3. SqlDataSource 컨트롤의 EnableCaching 속성을 true로 설정합니다.

    필터링을 지원하려면 쿼리에서 반환된 데이터를 캐싱해야 합니다.

  4. SqlDataSource 컨트롤의 CacheDuration 속성을 데이터를 캐싱할 시간(초)으로 설정합니다. 응용 프로그램에 따라 적절한 값을 선택합니다.

  5. 다음 예제처럼 컨트롤의 FilterExpression 속성을 반환할 데이터를 지정하는 식으로 설정합니다.

7번 설명 country = 'Germany'

필터 식 구문에 대한 자세한 내용은 RowFilter를 참조하십시오.

필터링을 사용하도록 설정된 SqlDataSource 컨트롤은 다음과 같은 형태가 됩니다.

<asp:SqlDataSource

ID="SqlDataSource1"

DataSourceMode="DataSet"

EnableCaching="true"

Runat="server"

SelectCommand="Select * From Customers" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

FilterExpression="

country = 'Germany'">

</asp:SqlDataSource>

위에는 별로 쓸모가 없네 ... 밑으로

매개 변수를 사용하여 SqlDataSource 컨트롤을 필터링하려면

  1. SqlDataSource 컨트롤의 FilterExpression 속성을 필터 매개 변수 값의 자리 표시자가 포함된 식으로 설정합니다. 자리 표시자에는 {n} 구문을 사용합니다. 여기서 n은 매개 변수의 순서를 나타냅니다.

    다음 예제에서는 매개 변수가 있는 필터 식을 보여 줍니다. 두 번째 필터 식에는 매개 변수 자리 표시자가 여러 개 포함되어 있습니다.

FilterExpression="category = '{0}'" FilterExpression="country = '{0}' AND city = '{1}'"

FilterParameters 요소를 SqlDataSource 요소의 자식으로 만듭니다. 각 필터 매개 변수 자리 표시자에 대해 다음 중 한 형식의 요소를 추가합니다.

  • ControlParameter

  • CookieParameter

  • FormParameter

  • ProfileParameter

  • SessionParameter

  • Parameter

다음 예제에서는 DropDownList 컨트롤에서 값을 가져오는 필터 매개 변수를 만드는

방법을 보여 줍니다.

<FilterParameters>

<asp:ControlParameter Name="CategoryList" ControlID="DropDownList1" PropertyValue="SelectedValue" />

</FilterParameters>

매개 변수의 Name 속성은 필수 속성입니다.

그러나 매개 변수는 이름이 아니라 순서에 따라 자리 표시자와 대응합니다.

<asp:SqlDataSource

ID="SqlDataSource1"

EnableCaching="true"

DataSourceMode="DataSet"

Runat="server"

SelectCommand="Select * from Customers" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>"

FilterExpression="

country = '{0}'">

<FilterParameters>

<asp:ControlParameter Name="countryparam" ControlID="DropDownList1" PropertyName="SelectedValue" /> <

/FilterParameters>

</asp:SqlDataSource>

사용자가 컨트롤 하기

사용자가 임의로 컨트롤 할 수 있따 아래는 삭제 예제 그럼 인설트 등등도 응용하면 되겠네

~~~

    protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
    {



        /* 예전에 는 이런방식으로.
        SqlConnection conn = new SqlConnection(AspxUtil.GetDBStr());
        conn.Open();
        SqlCommand comm = new SqlCommand("DELETE FROM COMMENT_BOARD WHERE IDX=@IDX", conn);
        comm.Parameters.Add("@IDX", SqlDbType.Int).Value = e.CommandArgument;
        comm.ExecuteNonQuery();        
        conn.Close();
        this.DataList1.DataBind();
        * */

간단하게 구현된거~ 열라간단하다

        SqlDataSource1.DeleteParameters["idx"].DefaultValue =      e.CommandArgument.ToString();
        SqlDataSource1.Delete();

    }

당연한 얘기지만 SqlDataSource에는 삭제 커멘드와

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ...

DeleteCommand="DELETE FROM [COMMENT_BOARD] WHERE [idx] = @idx"

/>

    <DeleteParameters>
        <asp:Parameter Name="idx" Type="Int32" />
    </DeleteParameters>

파라메터 값이 있어야 한다

사용자 임의 삭제 참고 MSDN

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.ko/dv_aspnetcon/html/44c76175-34b4-4dec-95d7-f9f6fd1fe00d.htm

http://msdn.microsoft.com/ko-kr/library/system.transactions.transactionscope.aspx

System.Transactions 인프라는 Transaction 클래스 기반의 명시적 프로그래밍 모델과 TransactionScope 클래스를 사용하는 암시적 프로그래밍 모델을 둘 다 제공합니다. 후자의 경우 인프라에서 자동으로 트랜잭션을 관리합니다.

new 문으로 TransactionScope를 인스턴스화하면 트랜잭션 관리자가 참여할 트랜잭션을 결정합니다. 결정 후에는 이 범위가 항상 해당 트랜잭션에 참여합니다. 앰비언트 트랜잭션이 있는지 여부와 생성자에 있는 TransactionScopeOption 매개 변수의 값에 따라 참여할 트랜잭션이 결정됩니다. 앰비언트 트랜잭션이란 해당 코드가 실행되는 트랜잭션입니다. Transaction 클래스의 정적 Current 속성을 호출하면 앰비언트 트랜잭션에 대한 참조를 가져올 수 있습니다. 이 매개 변수의 사용 방법에 대한 자세한 내용은 트랜잭션 범위를 사용하여 암시적 트랜잭션 구현 항목의 "트랜잭션 흐름 관리" 단원을 참조하십시오.

트랜잭션 범위(즉, TransactionScope 개체 초기화와 Dispose 메서드 호출 사이)에서 예외가 발생하지 않으면 범위가 참여하는 트랜잭션을 계속할 수 있습니다. 트랜잭션 범위에 예외가 발생하면 범위가 참여하는 트랜잭션이 롤백됩니다.

응용 프로그램이 트랜잭션에서 수행할 작업을 모두 완료하면 Complete 메서드를 한 번만 호출하여 트랜잭션 커밋이 허용됨을 트랜잭션 관리자에게 알려야 합니다. 이 메서드를 호출하지 못하면 트랜잭션이 중단됩니다.

Dispose 메서드를 호출하면 트랜잭션 범위의 끝이 표시됩니다. 이 메서드를 호출한 후에 발생하는 예외는 트랜잭션에 영향을 주지 않습니다.

범위 안의 Current 값을 수정하면 Dispose를 호출할 경우 예외가 throw됩니다. 그러나 범위 끝에서 이전 값이 복원됩니다. 또한 트랜잭션을 만든 트랜잭션 범위 안의 Current에서 Dispose를 호출하면 범위 끝에서 트랜잭션이 중단됩니다.

// This function takes arguments for 2 connection strings and commands to create a transaction 
// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the 
// transaction is rolled back. To test this code, you can connect to two different databases 
// on the same server by altering the connection string, or to another 3rd party RDBMS by 
// altering the code in the connection2 code block.
static public int CreateTransactionScope(
    string connectString1, string connectString2,
    string commandText1, string commandText2)
{
    // Initialize the return value to zero and create a StringWriter to display results.
    int returnValue = 0;
    System.IO.StringWriter writer = new System.IO.StringWriter();

    // Create the TransactionScope to execute the commands, guaranteeing
    // that both commands can commit or roll back as a single unit of work.
    using (TransactionScope scope = new TransactionScope())
    {
        using (SqlConnection connection1 = new SqlConnection(connectString1))
        {
            try
            {
                // Opening the connection automatically enlists it in the 
                // TransactionScope as a lightweight transaction.
                connection1.Open();

                // Create the SqlCommand object and execute the first command.
                SqlCommand command1 = new SqlCommand(commandText1, connection1);
                returnValue = command1.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                // If you get here, this means that command1 succeeded. By nesting
                // the using block for connection2 inside that of connection1, you
                // conserve server and network resources as connection2 is opened
                // only when there is a chance that the transaction can commit.   
                using (SqlConnection connection2 = new SqlConnection(connectString2))
                    try
                    {
                        // The transaction is escalated to a full distributed
                        // transaction when connection2 is opened.
                        connection2.Open();

                        // Execute the second command in the second database.
                        returnValue = 0;
                        SqlCommand command2 = new SqlCommand(commandText2, connection2);
                        returnValue = command2.ExecuteNonQuery();
                        writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
                    }
                    catch (Exception ex)
                    {
                        // Display information that command2 failed.
                        writer.WriteLine("returnValue for command2: {0}", returnValue);
                        writer.WriteLine("Exception Message2: {0}", ex.Message);
                    }
            }
            catch (Exception ex)
            {
                // Display information that command1 failed.
                writer.WriteLine("returnValue for command1: {0}", returnValue);
                writer.WriteLine("Exception Message1: {0}", ex.Message);
            }
        }

        // The Complete method commits the transaction. If an exception has been thrown,
        // Complete is not  called and the transaction is rolled back.
        scope.Complete();
    }

    // The returnValue is greater than 0 if the transaction committed.
    if (returnValue > 0)
    {
        writer.WriteLine("Transaction was committed.");
    }
    else
    {
        // You could write additional business logic here, for example, you can notify the caller 
        // by throwing a TransactionAbortedException, or logging the failure.
        writer.WriteLine("Transaction rolled back.");
    }

    // Display messages.
    Console.WriteLine(writer.ToString());

    return returnValue;
} 
public partial class Sql_OracleDefault : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        OracleConnection conn = new OracleConnection("연결문자열");
        conn.Open();
        OracleCommand comm = new OracleCommand(this.TextBox1.Text, conn);
        OracleDataReader rs =   comm.ExecuteReader();
        DataTable dt =        rs.GetSchemaTable();
        this.TextBox2.Text = string.Empty;
        
            while (rs.Read() ) {
                 for (int ii = 0; ii < rs.FieldCount; ii++) {
						//rs.GetName(ii) 컬럼이름

                     this.TextBox2.Text +=  rs.GetName(ii) + ": " + rs[ii].ToString() + "\n ";
                   
                 }
                 this.TextBox2.Text += "---------------------------------------------";
                 this.TextBox2.Text += "\n";
             }
         
     

            conn.Close();
    }
}

+ Recent posts