Using Transaction Isolation Levels to Protect Data
Số trang: 5
Loại file: pdf
Dung lượng: 20.99 KB
Lượt xem: 9
Lượt tải: 0
Xem trước 2 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
[ Team LiB ] Recipe 6.12 Using Transaction Isolation Levels to Protect Data Problem You want to effectively use transaction isolation levels to ensure data consistency for a range of data rows. Solution Set and use isolation levels as shown in the following example.
Nội dung trích xuất từ tài liệu:
Using Transaction Isolation Levels to Protect Data[ Team LiB ]Recipe 6.12 Using Transaction Isolation Levels to Protect DataProblemYou want to effectively use transaction isolation levels to ensure data consistency for arange of data rows.SolutionSet and use isolation levels as shown in the following example.The sample code contains three event handlers:Start Tran Button.Click Opens a Connection and starts a transaction with the specified isolation level: Chaos, ReadCommitted, ReadUncommitted, RepeatableRead, Serializable, or Unspecified. Within the transaction, a DataTable is filled with the Orders table from the Northwind database. The default view of the table is bound to the data grid on the form.Cancel Button.Click Rolls back the transaction, closes the connection, and clears the data grid.Form.Closing Rolls back the transaction and closes the connection.The C# code is shown in Example 6-30.Example 6-30. File: TransactionIsolationLevelsForm.cs// Namespaces, variables, and constantsusing System;using System.Configuration;using System.Windows.Forms;using System.Data;using System.Data.SqlClient;private SqlConnection conn;private SqlTransaction tran;// . . .private void startButton_Click(object sender, System.EventArgs e){ startButton.Enabled = false; // Get the user-defined isolation level. IsolationLevel il = IsolationLevel.Unspecified; if(chaosRadioButton.Checked) il = IsolationLevel.Chaos; else if(readCommittedRadioButton.Checked) il = IsolationLevel.ReadCommitted; else if(readUncommittedRadioButton.Checked) il = IsolationLevel.ReadUncommitted; else if(repeatableReadRadioButton.Checked) il = IsolationLevel.RepeatableRead; else if(serializableRadioButton.Checked) il = IsolationLevel.Serializable; else if(unspecifiedRadioButton.Checked) il = IsolationLevel.Unspecified; // Open a connection. conn = new SqlConnection( ConfigurationSettings.AppSettings[Sql_ConnectString]); conn.Open( ); try { // Start a transaction. tran = conn.BeginTransaction(il); } catch(Exception ex) { // Could not start the transaction. Close the connection. conn.Close( ); MessageBox.Show(ex.Message,Transaction Isolation Levels, MessageBoxButtons.OK, MessageBoxIcon.Error); startButton.Enabled = true; return; } String sqlText = SELECT * FROM Orders; // Create a command using the transaction. SqlCommand cmd = new SqlCommand(sqlText, conn, tran); // Create a DataAdapter to retrieve all Orders. SqlDataAdapter da = new SqlDataAdapter(cmd); // Define a CommandBuilder for the DataAdapter. SqlCommandBuilder cb = new SqlCommandBuilder(da); // Fill table with Orders. DataTable dt = new DataTable( ); da.Fill(dt); // Bind the default view of the table to the grid. dataGrid.DataSource = dt.DefaultView; cancelButton.Enabled = true; dataGrid.ReadOnly = false;}private void cancelButton_Click(object sender, System.EventArgs e){ cancelButton.Enabled = false; dataGrid.ReadOnly = true; // Roll back the transaction and close the connection. tran.Rollback( ); conn.Close( ); // Unbind the grid. dataGrid.DataSource = null; startButton.Enabled = true;}private void UsingLockingHintsForPessimisticLockingForm_Closing( object sender, System.ComponentModel.CancelEventArgs e){ // Roll back the transaction and close the connection. tran.Rollback( ); conn.Close( );}DiscussionThe isolation level specifies the transaction locking behavior for a connection. Itdetermines what changes made to data within a transaction are visible outside of thetransaction while the transaction is uncommitted.Concurrency violations occur when multiple users or processes attempt to modify thesame data in a database at the same time without locking. Table 6-16 describesconcurrency problems. Table 6-16. Concurrency problems Condition Description Two or more transactions select the same row and subsequentlyLost Update update that row. Data is lost because the transactions are unaware of each other and overwrite each others updates. A second transaction selects a row that has been updated, but notUncommitted committed, by another transaction. The first transaction makesDependency (Dirty more changes to the data or rolls back the changes already madeRead) resulting in the second transaction having invalid data.Inconsistent Analysis A second transaction reads different data each time that the same(Nonrepeatable row is read. Another transaction has changed and committed theRead) data between the reads. An insert or delete is performed for a row belonging to a range of rows being read by a transaction. The rows selected by thePhantom Read transaction are missing the inserted rows and still contain the deleted rows that no longer exist.Locks ensure transactional integrity and maintain database consistency by controllinghow resources can be accessed by concurrent transactions. A lock is an object indicatingthat a user has a dependency on a resource. It prevents other users from performingoperations that would adversely affect the locked resources. Locks are acquired andreleased by user actions; they are managed internally by database software. Table 6-17lists and describes resource lock modes used by ADO.NET. Table 6-17. Resource lock modes Lock Descripti ...
Nội dung trích xuất từ tài liệu:
Using Transaction Isolation Levels to Protect Data[ Team LiB ]Recipe 6.12 Using Transaction Isolation Levels to Protect DataProblemYou want to effectively use transaction isolation levels to ensure data consistency for arange of data rows.SolutionSet and use isolation levels as shown in the following example.The sample code contains three event handlers:Start Tran Button.Click Opens a Connection and starts a transaction with the specified isolation level: Chaos, ReadCommitted, ReadUncommitted, RepeatableRead, Serializable, or Unspecified. Within the transaction, a DataTable is filled with the Orders table from the Northwind database. The default view of the table is bound to the data grid on the form.Cancel Button.Click Rolls back the transaction, closes the connection, and clears the data grid.Form.Closing Rolls back the transaction and closes the connection.The C# code is shown in Example 6-30.Example 6-30. File: TransactionIsolationLevelsForm.cs// Namespaces, variables, and constantsusing System;using System.Configuration;using System.Windows.Forms;using System.Data;using System.Data.SqlClient;private SqlConnection conn;private SqlTransaction tran;// . . .private void startButton_Click(object sender, System.EventArgs e){ startButton.Enabled = false; // Get the user-defined isolation level. IsolationLevel il = IsolationLevel.Unspecified; if(chaosRadioButton.Checked) il = IsolationLevel.Chaos; else if(readCommittedRadioButton.Checked) il = IsolationLevel.ReadCommitted; else if(readUncommittedRadioButton.Checked) il = IsolationLevel.ReadUncommitted; else if(repeatableReadRadioButton.Checked) il = IsolationLevel.RepeatableRead; else if(serializableRadioButton.Checked) il = IsolationLevel.Serializable; else if(unspecifiedRadioButton.Checked) il = IsolationLevel.Unspecified; // Open a connection. conn = new SqlConnection( ConfigurationSettings.AppSettings[Sql_ConnectString]); conn.Open( ); try { // Start a transaction. tran = conn.BeginTransaction(il); } catch(Exception ex) { // Could not start the transaction. Close the connection. conn.Close( ); MessageBox.Show(ex.Message,Transaction Isolation Levels, MessageBoxButtons.OK, MessageBoxIcon.Error); startButton.Enabled = true; return; } String sqlText = SELECT * FROM Orders; // Create a command using the transaction. SqlCommand cmd = new SqlCommand(sqlText, conn, tran); // Create a DataAdapter to retrieve all Orders. SqlDataAdapter da = new SqlDataAdapter(cmd); // Define a CommandBuilder for the DataAdapter. SqlCommandBuilder cb = new SqlCommandBuilder(da); // Fill table with Orders. DataTable dt = new DataTable( ); da.Fill(dt); // Bind the default view of the table to the grid. dataGrid.DataSource = dt.DefaultView; cancelButton.Enabled = true; dataGrid.ReadOnly = false;}private void cancelButton_Click(object sender, System.EventArgs e){ cancelButton.Enabled = false; dataGrid.ReadOnly = true; // Roll back the transaction and close the connection. tran.Rollback( ); conn.Close( ); // Unbind the grid. dataGrid.DataSource = null; startButton.Enabled = true;}private void UsingLockingHintsForPessimisticLockingForm_Closing( object sender, System.ComponentModel.CancelEventArgs e){ // Roll back the transaction and close the connection. tran.Rollback( ); conn.Close( );}DiscussionThe isolation level specifies the transaction locking behavior for a connection. Itdetermines what changes made to data within a transaction are visible outside of thetransaction while the transaction is uncommitted.Concurrency violations occur when multiple users or processes attempt to modify thesame data in a database at the same time without locking. Table 6-16 describesconcurrency problems. Table 6-16. Concurrency problems Condition Description Two or more transactions select the same row and subsequentlyLost Update update that row. Data is lost because the transactions are unaware of each other and overwrite each others updates. A second transaction selects a row that has been updated, but notUncommitted committed, by another transaction. The first transaction makesDependency (Dirty more changes to the data or rolls back the changes already madeRead) resulting in the second transaction having invalid data.Inconsistent Analysis A second transaction reads different data each time that the same(Nonrepeatable row is read. Another transaction has changed and committed theRead) data between the reads. An insert or delete is performed for a row belonging to a range of rows being read by a transaction. The rows selected by thePhantom Read transaction are missing the inserted rows and still contain the deleted rows that no longer exist.Locks ensure transactional integrity and maintain database consistency by controllinghow resources can be accessed by concurrent transactions. A lock is an object indicatingthat a user has a dependency on a resource. It prevents other users from performingoperations that would adversely affect the locked resources. Locks are acquired andreleased by user actions; they are managed internally by database software. Table 6-17lists and describes resource lock modes used by ADO.NET. Table 6-17. Resource lock modes Lock Descripti ...
Tìm kiếm theo từ khóa liên quan:
công nghệ thông tin kỹ thuật lập trình Oreilly Ado Dot Net Cookbook Ebook-Lib Displaying an Image from a Database in a Web Forms ControlTài liệu liên quan:
-
52 trang 434 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 321 0 0 -
74 trang 304 0 0
-
96 trang 299 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 293 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 286 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 277 0 0 -
Kỹ thuật lập trình trên Visual Basic 2005
148 trang 270 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 270 0 0 -
Tài liệu dạy học môn Tin học trong chương trình đào tạo trình độ cao đẳng
348 trang 269 1 0