System.Data Namespace IDbConnection Class
Begins a database transaction.
1. Begins a database transaction.
2. Begins a database transaction with the specified isolation level.
The following example initializes an SqlConnection and an SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.
NOTE: This example uses one of the overloaded versions of BeginTransaction. For other examples that may be available, see the individual overload topics.
void RunSqlTransaction ( string connString ) {
SqlConnection myConn = new SqlConnection ( connString );
myConn.Open ( );
SqlCommand myCommand = new SqlCommand ( );
SqlTransaction myTrans;
// start a local transaction
myTrans = myConn.BeginTransaction ( IsolationLevel.ReadCommitted );
// 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.ToIsolationLevel ( ) );
Response.Write ( "No record written to database." );
} finally {
myConn.Close ( );
}
}
Public Sub RunSqlTransaction ( connString As IsolationLevel )
Dim myConn As New SqlConnection ( connString )
myConn.Open ( )
Dim myCommand As New SqlCommand ( )
Dim myTrans As SqlTransaction
' start a local transaction
myTrans = myConn.BeginTransaction ( IsolationLevel.ReadCommitted )
' 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.ToIsolationLevel ( ) )
Response.Write ( "No record written to database." )
Finally
myConn.Close ( )
End Try
End Sub |
|
C# |
VB |
IDbConnection Members IDbTransaction