SqlCeConnection.BeginTransaction 메서드

데이터베이스 트랜잭션을 시작합니다.

네임스페이스:  System.Data.SqlServerCe
어셈블리:  System.Data.SqlServerCe(System.Data.SqlServerCe.dll)

public SqlCeTransaction BeginTransaction()

반환 값

유형: System.Data.SqlServerCe.SqlCeTransaction
새 트랜잭션을 나타내는 개체입니다.

Commit 또는 Rollback 메서드를 사용하여 명시적으로 트랜잭션을 커밋하거나 롤백해야 합니다.

다음 예제에서는 SqlCeConnectionSqlCeTransaction을 만든 다음 BeginTransaction, CommitRollback 메서드를 사용하는 방법을 보여 줍니다.

SqlCeConnection conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
conn.Open();

// Start a local transaction
//
SqlCeTransaction tx = conn.BeginTransaction();

// By default, commands run in auto-commit mode; 
//
SqlCeCommand cmd1 = conn.CreateCommand();

// You may create multiple commands on the same connection
//
SqlCeCommand cmd2 = conn.CreateCommand();

// To enlist a command in a transaction, set the Transaction property
//
cmd1.Transaction = tx;

try
{
    cmd1.CommandText = "INSERT INTO Shippers ([Company Name]) VALUES ('Northwind Traders')";
    cmd1.ExecuteNonQuery();

    // Auto-commited because cmd2 is not enlisted in a transaction
    //
    cmd2.CommandText = "INSERT INTO Employees ([Last Name], [First Name]) VALUES ('Decker', 'Barbara')";
    cmd2.ExecuteNonQuery();

    // This will cause referential constraint violation
    //
    cmd1.CommandText = "DELETE FROM Products WHERE [Product ID] = 1";
    cmd1.ExecuteNonQuery();

    // Commit the changes to disk if everything above succeeded
    //
    tx.Commit();
}
catch (Exception)
{
    tx.Rollback();
}
finally
{
    conn.Close();
}


표시: