General
Sqltransaction tn; // declare a transaction
Const string SQL = "insert into employees1 (empid) values (@ userid )";
Sqlconnection Cn = new sqlconnection ("Data Source = AUG-SQLSRV; initial catalog = HumanResources; Integrated Security = sspi ");
Try... {If (CN. State! = Connectionstate. Open)... {CN. open ();}}
// If we throw an exception on open, which is a 'Risky 'Operation
// Manually make the assertino fail by setting it to false and use
// Ex. tostring () to get the information about the exception.
Catch (sqlexception ex)... {Debug. Assert (false, Ex. tostring ());}
// Instantiate command with commandtext and connection and T // transaction
Tn = cn. begintransaction ();
Sqlcommand cmd = new sqlcommand (SQL, CN, TN );
Cmd. Parameters. Clear ();
Cmd. Parameters. Add ("@ userid", sqldbtype. INT). value = 314;
Try
...{
// You can test for records affected, in this case we know it
// Wocould be at most one record.
Int I = cmd. executenonquery ();
// If successful, commit the transaction
// Loop 5 times and just add the ID's incremented each time
For (INT x = 0; x <5; X ++)
...{
Cmd. Parameters ["@ userid"]. value = (315 + x );
Cmd. executenonquery ();
}
Cmd. Parameters ["@ userid"]. value = (325 );
Cmd. executenonquery ();
Tn. Commit ();
}
Catch (sqlexception ex )...{
Debug. Assert (false, Ex. tostring ());
// If it failed for whatever reason, rollback the // transaction
Tn. rollback ();
// No need to throw because we are at a top level call and // nothing is handling exceptions
}
Finally ...{
// Check for close and respond accordingly
If (CN. State! = Connectionstate. Closed)... {CN. Close ();}
// Clean up my mess
CN. Dispose ();
Cmd. Dispose ();
Tn. Dispose ();
}
Use transaction in sqlhelper
Public static dataset geticcontact (string ICID)
...{
Sqlconnection conn = getconnection ();
Sqltransaction Tn = NULL;
Try
...{
If (conn. State! = Connectionstate. open)
...{
Conn. open ();
}
Tn = conn. begintransaction ();
Sqlparameter [] arparams = new sqlparameter [1];
If (system. configuration. configurationsettings. Fig ["cachemssqlparameters"]. tolower () = "true ")
...{
Arparams = sqlhelperparametercache. getspparameterset (getconnectionstring (),
"Usp_ic_contact ");
Arparams [0]. value = ICID;
}
Else
...{
Arparams [0] = new sqlparameter ("@ ICID", sqldbtype. nvarchar, 50 );
Arparams [0]. Direction = parameterdirection. input;
Arparams [0]. value = ICID;
}
Dataset DS = sqlhelper. executedataset (TN, commandtype. storedprocedure, "usp_ic_contact", arparams );
Tn. Commit ();
Return Ds;
}
Catch (system. Exception E)
...{
Tn. rollback ();
Return NULL;
}
Finally
...{
If (conn. State! = Connectionstate. Closed)... {conn. Close ();}
Conn. Dispose ();
Tn. Dispose ();
}
}