SqlConnection.BeginTransaction Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Overloads
BeginTransaction() |
Starts a database transaction. |
BeginTransaction(IsolationLevel) |
Starts a database transaction with the specified isolation level. |
BeginTransaction(String) |
Starts a database transaction with the specified transaction name. |
BeginTransaction(IsolationLevel, String) |
Starts a database transaction with the specified isolation level and transaction name. |
BeginTransaction()
Starts a database transaction.
public:
Microsoft::Data::SqlClient::SqlTransaction ^ BeginTransaction();
public Microsoft.Data.SqlClient.SqlTransaction BeginTransaction ();
override this.BeginTransaction : unit -> Microsoft.Data.SqlClient.SqlTransaction
Public Function BeginTransaction () As SqlTransaction
Returns
An object representing the new transaction.
Exceptions
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).
Parallel transactions are not supported.
Examples
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.
using Microsoft.Data.SqlClient;
namespace Transaction1CS
{
class Program
{
static void Main()
{
string connectionString =
"Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)";
ExecuteSqlTransaction(connectionString);
Console.ReadLine();
}
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();
// 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();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}
}
Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
You must explicitly commit or roll back the transaction using the Commit or Rollback method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
Note
If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the BeginTransaction method, use the overload that takes the iso
parameter (BeginTransaction). The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed. Setting the isolation level to Snapshot in a database where the snapshot isolation level is not enabled does not throw an exception. The transaction will complete using the default isolation level.
Caution
If a transaction is started and a level 16 or higher error occurs on the server, the transaction will not be rolled back until the Read method is invoked. No exception is thrown on ExecuteReader.
Caution
When your query returns a large amount of data and calls BeginTransaction
, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
For more information on SQL Server transactions, see Transactions (Transact-SQL).
Applies to
BeginTransaction(IsolationLevel)
Starts a database transaction with the specified isolation level.
public:
Microsoft::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso);
public Microsoft.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso);
override this.BeginTransaction : System.Data.IsolationLevel -> Microsoft.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel) As SqlTransaction
Parameters
- iso
- IsolationLevel
The isolation level under which the transaction should run.
Returns
An object representing the new transaction.
Exceptions
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).
Parallel transactions are not supported.
Examples
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)";
ExecuteSqlTransaction(connectionString);
Console.ReadLine();
}
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.");
}
}
}
}
Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
You must explicitly commit or roll back the transaction using the Commit or Rollback method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
Note
After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call SqlConnection.BeginTransaction followed immediately by SqlTransaction.Commit. For more information on SQL Server isolation levels, see Transaction Isolation Levels.
For more information on SQL Server transactions, see Transactions (Transact-SQL).
Caution
When your query returns a large amount of data and calls BeginTransaction
, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
Applies to
BeginTransaction(String)
Starts a database transaction with the specified transaction name.
public:
Microsoft::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::String ^ transactionName);
public Microsoft.Data.SqlClient.SqlTransaction BeginTransaction (string transactionName);
override this.BeginTransaction : string -> Microsoft.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (transactionName As String) As SqlTransaction
Parameters
- transactionName
- String
The name of the transaction.
Returns
An object representing the new transaction.
Exceptions
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).
Parallel transactions are not supported.
Examples
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.
using Microsoft.Data.SqlClient;
namespace Transaction1CS
{
class Program
{
static void Main()
{
string connectionString =
"Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)";
ExecuteSqlTransaction(connectionString);
Console.ReadLine();
}
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("SampleTransaction");
// 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();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback("SampleTransaction");
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}
}
Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
The length of the transactionName
parameter must not exceed 32 characters; otherwise an exception will be thrown.
The value in the transactionName
parameter can be used in later calls to Rollback and in the savePoint
parameter of the Save method.
You must explicitly commit or roll back the transaction using the Commit or Rollback method. To make sure that the .NET Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
For more information on SQL Server transactions, see Transactions (Transact-SQL).
Caution
When your query returns a large amount of data and calls BeginTransaction
, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
Applies to
BeginTransaction(IsolationLevel, String)
Starts a database transaction with the specified isolation level and transaction name.
public:
Microsoft::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso, System::String ^ transactionName);
public Microsoft.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso, string transactionName);
override this.BeginTransaction : System.Data.IsolationLevel * string -> Microsoft.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel, transactionName As String) As SqlTransaction
Parameters
- iso
- IsolationLevel
The isolation level under which the transaction should run.
- transactionName
- String
The name of the transaction.
Returns
An object representing the new transaction.
Exceptions
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).
Parallel transactions are not supported.
Examples
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.
using Microsoft.Data.SqlClient;
namespace Transaction1CS
{
class Program
{
static void Main()
{
string connectionString =
"Persist Security Info=False;Integrated Security=SSPI;database=Northwind;server=(local)";
ExecuteSqlTransaction(connectionString);
Console.ReadLine();
}
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, "SampleTransaction");
// 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("SampleTransaction");
}
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.");
}
}
}
}
}
Remarks
This command maps to the SQL Server implementation of BEGIN TRANSACTION.
The value in the transactionName
parameter can be used in later calls to Rollback and in the savePoint
parameter of the Save method.
You must explicitly commit or roll back the transaction using the Commit or Rollback method. To make sure that the SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
Note
After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call SqlConnection.BeginTransaction followed immediately by SqlTransaction.Commit. For more information on SQL Server isolation levels, see Transaction Isolation Levels.
For more information on SQL Server transactions, see Transactions (Transact-SQL).
Caution
When your query returns a large amount of data and calls BeginTransaction
, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.