Now we understand the concepts and principles of transactions and have some basic knowledge as well.C #Developers, we are already familiar with writing database interactionsProgramThe following are some key points:
(1) UseSqlconnectionClass ObjectOpen ()Method to establish a connection with the database server.
(2) And then assign the connectionSqlcommandObjectConnectionAttribute.
(3) Will be executedSQLStatementSqlcommandOfCommandtextAttribute.
( 4 ) use sqlcommand object for database operations.
Create A ADO. net transactions are simple. You need to define an object of the sqltransaction type. sqlconnection and oledbconnection has a begintransaction method, it can return sqltransaction or oledbtransaction object. Then, assign the sqlcommand Object transcation attribute. In order for the transaction to be processed successfully, you must call sqltransaction commit () method of the object. If an error occurs, you must call the rollback () method to cancel all operations.
Based on the above understanding, we will start to writeAdo. net.
(Example location: CD\ Code \ ch05 \ 04 \ WEB \ webform2)
String constring = "Data Source = 127.0.0.1; database = codematic; user id = sa;
Password = ";
Sqlconnection myconnection = new sqlconnection (constring );
Myconnection. open ();
//Start a transaction
Sqltransaction mytrans = myconnection. begintransaction ();
//Create a command for the transaction
Sqlcommand mycommand = new sqlcommand ();
Mycommand. Connection = myconnection;
Mycommand. Transaction = mytrans;
Try
{
Mycommand. commandtext = "Update p_product set name ='Computer2 'where id = 52 ";
Mycommand. executenonquery ();
Mycommand. commandtext = "Update p_product set name ='Computer3 'where id = 53 ";
Mycommand. executenonquery ();
Mytrans. Commit ();//Submit
Response. Write ("Two data entries updated successfully");
}
Catch (exception ex)
{
Mytrans. rollback ();//Rollback in case of an error
Response. Write (ex. tostring ());
}
Finally
{
Myconnection. Close ();
}
Ado. netThe advantages and limitations of transactions are as follows.
Advantages:
L simple.
L and database transactions are almost fast.
L transactions can be accessed across multiple databases.
L independent from the database, the proprietary code of different databases is hidden.
Restrictions: transactions are executed on the database connection layer. Therefore, you must manually maintain a connection during the transaction execution.