SqlConnection.Transaction
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception e)
{
try
{
transaction.Rollback();
}
catch (SqlException ex)
{
if (transaction.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
Console.WriteLine("An exception of type " + e.GetType() +
" was encountered while inserting the data.");
Console.WriteLine("Neither record was written to database.");
}
}
}
비고] 격리 수준
멤버 이름 | 설명 | |
---|---|---|
Serializable | 트랜잭션을 수행하는 동안 일시적 데이터를 읽을 수 있지만 수정할 수는 없으며 새 데이터를 추가할 수도 없습니다. | |
RepeatableRead | 트랜잭션을 수행하는 동안 일시적 데이터를 읽을 수 있지만 수정할 수는 없습니다. 트랜잭션을 수행하는 동안 새 데이터를 추가할 수 있습니다. | |
ReadCommitted | 트랜잭션을 수행하는 동안 일시적 데이터를 읽을 수 없지만 수정할 수는 있습니다. | |
ReadUncommitted | 트랜잭션을 수행하는 동안 일시적 데이터를 읽고 수정할 수 있습니다. | |
Snapshot | 일시적 데이터를 읽을 수 있습니다. 트랜잭션은 데이터를 수정하기 전에, 데이터가 처음 읽혀진 후 다른 트랜잭션이 이 데이터를 변경했는지 확인합니다. 데이터가 업데이트된 경우 오류가 발생합니다. 이 경우 트랜잭션이 이전에 커밋된 데이터 값에 영향을 미칠 수 있습니다. | |
Chaos | 격리 수준이 높은 트랜잭션에서 보류 중인 변경은 덮어쓸 수 없습니다. | |
Unspecified | 지정된 격리 수준과 다른 수준이 사용되지만 수준을 결정할 수는 없습니다. 이 값을 설정하면 예외가 throw됩니다. |