System.Data.SqlClient Namespace SqlConnection Class
Begins a database transaction.
[ VB ]
Overloads Overrides Public Function BeginTransaction ( ) As SqlTransaction
[ C# ]
public override SqlTransaction BeginTransaction ( );
[ C++ ]
public: SqlTransaction BeginTransaction ( );
[ JScript ]
public override function BeginTransaction ( ) : SqlTransaction
An object representing the new transaction.
This command maps to the SQL Server™ implementation of BEGIN TRANSACTION.
You must explicity commit or roll back the transaction using the Commit or Rollback method. To ensure that the SQL Server .NET Data Provider transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
For more information, see the SQL Server™ documentation, particularly on how nested transactions are handled.
The following example initializes an SqlConnection, opens it, begins a transaction, commits the transaction, then closes the connection.
void RunSqlTransaction ( string connString ) {
SqlConnection myConn = new SqlConnection ( connString );
myConn.Open ( );
SqlCommand myCommand = new SqlCommand ( );
SqlTransaction myTrans;
// start a local transaction
myTrans = myConn.BeginTransaction ( );
// assign transaction object for a pending local transaction
myCommand.Transaction = myTrans;
try {
myCommand.CommandText = "Insert into Region (
RegionID, RegionDescription ) VALUES ( 100, 'Description' ) ";
myCommand.ExecuteNonQuery ( );
myTrans.Commit ( );
Response.Write ( "One record written to database." );
} catch ( Exception e ) {
myTrans.Rollback ( );
Response.Write ( e.ToString ( ) );
Response.Write ( "No record written to database." );
} finally {
myConn.Close ( );
}
}
Public Sub RunSqlTransaction ( connString As String )
Dim myConn As New SqlConnection ( connString )
myConn.Open ( )
Dim myCommand As New SqlCommand ( )
Dim myTrans As SqlTransaction
' start a local transaction
myTrans = myConn.BeginTransaction ( )
' assign transaction object for a pending local transaction
myCommand.Transaction = myTrans
Try
myCommand.CommandText = "Insert into Region ( &_
RegionID, RegionDescription ) VALUES ( 100, 'Description' ) "
myCommand.ExecuteNonQuery ( )
myTrans.Commit ( )
Response.Write ( "One record written to database." )
Catch e As Exception
myTrans.Rollback ( )
Response.Write ( e.ToString ( ) )
Response.Write ( "No record written to database." )
Finally
myConn.Close ( )
End Try
End Sub |
|
C# |
VB |
SqlConnection Members SqlConnection.BeginTransaction Overload List Commit Save Rollback