tailieunhanh - Using Manual Transactions

[ Team LiB ] Recipe Using Manual Transactions Problem You need to explicitly begin, control, and end a transaction within a .NET application. Solution Use the Connection object with structured exceptions (try . . . catch . . . finally). | Team LiB Recipe Using Manual Transactions Problem You need to explicitly begin control and end a transaction within a .NET application. Solution Use the Connection object with structured exceptions try . . . catch . . . finally . The sample code contains two event handlers Sets up the sample by filling a DataTable with the Categories table from the Northwind sample database. The default view of the table is bound to a data grid on the form. Insert Inserts user-entered data for two Categories records into the Northwind database within a manual transaction. If either record insert fails both inserts are rolled back otherwise both record inserts are committed. The C code is shown in Example 6-3. Example 6-3. File Namespaces variables and constants using System using using using using private const String CATEGORIES_TABLE Categories private DataTable dt private SqlDataAdapter da . . . private void ManualTransactionForm_Load object sender e Fill the categories table. String sqlText SELECT CategorylD CategoryName Description FROM Categories da new SqlDataAdapter sqlText S ql_ConnectString dt new DataTable CATEGORIES_TABLE dt dt Bind the default view of the table to the grid. private void insertButton_Click object sender e String sqlText INSERT CATEGORIES_TABLE CategoryName Description VALUES @CategoryName @Description Create the connection. SqlConnection conn new SqlConnection S ql_ConnectString Create the transaction. SqlTransaction tran Create command in the transaction with parameters. SqlCommand cmd new SqlCommand sqlText conn tran new SqlParameter @CategoryName 15 new .