Now that we have a sense of the concepts and principles of the business, and as a C # developer who already has some foundation, we are already familiar with some of the key elements of writing a database interaction program:
(1) Use the Open () method of the object of the SqlConnection class to establish a connection to the database server.
(2) The connection is then assigned to the Connection property of the SqlCommand object.
(3) Assign the SQL statement you want to execute to the CommandText property of SqlCommand .
(4) database operation via SqlCommand object.
Creating an ADO transaction is simple and requires defining an object of type sqltransaction . Both the SqlConnection and OleDbConnection objects have a BeginTransaction method that can return sqltransaction Or a oledbtransaction object. The transcation property of the SqlCommand object is then assigned to the Association of the two. For the transaction to complete successfully, you must call the Commit () method of the sqltransaction object. If there is an error, you must call the Rollback () method to undo all operations.
Key points of the transaction handler:
(1) Create a transaction
(2) The transaction is associated with each command to be processed.
(3) Commit and rollback of a transaction
based on this understanding, let's start by writing a ADO transaction handler.
stringConstring ="data source=127.0.0.1;database=codematic;user Id=sa;Password=";SqlConnection myconnection=NewSqlConnection (constring); Myconnection.open ();//Start a transactionsqltransaction Mytrans=myconnection.begintransaction ();//Create a command for a transactionSqlCommand mycommand=NewSqlCommand (); Mycommand.connection=myconnection;mycommand.transaction=Mytrans;Try{myCommand.CommandText="Update p_product set name= ' Computer 2 ' where id=52"; Mycommand.executenonquery (); myCommand.CommandText="Update p_product set name= ' Computer 3 ' where id=53"; Mycommand.executenonquery (); Mytrans.commit ();//SubmitResponse.Write ("two data Update successful");}Catch(Exception ex) {mytrans.rollback ();//error encountered, rollbackResponse.Write (ex. ToString ()); }finally{myconnection.close ();}
The advantages and limitations of ADO are as follows.
Advantage:
L Simple.
L and database transactions are almost fast.
L transactions can be accessed across multiple databases.
L Separate from the database, the proprietary code of different databases is hidden.
Restriction: Transaction execution is on the database connection layer, so a connection needs to be maintained manually during the execution of the transaction.
Note |
All commands must be associated on the same connection instance, ADO. NET transaction processing does not support transactions that span multiple connections. |
Selected from "Liang Jian. NET." NET in-depth experience and combat Essentials Book 5.4.
. NET-Development transactions---ADO-level transactions