6.14. Specifying Locking Hints in a SQL Server Database

Problem

You need to pessimistically lock rows in an underlying SQL Server database.

Solution

Use SQL Server locking hints from ADO.NET.

The sample code contains three event handlers:

Start Tran Button.Click

Creates a SQL SELECT statement to retrieve the Orders table from the Northwind database. A locking hint, either UPDLOCK or HOLDLOCK, is added to the statement as specified. A Connection is opened and a Transaction started on it with an isolation level of ReadCommitted. A DataAdapter is used on the transacted connection to fill a DataTable. A CommandBuilder is created to generate updating logic. The default view of the table is bound to the data grid on the form.

Cancel Button.Click

Clears the data grid, rolls back the transaction, and closes the connection.

Form.Closing

Rolls back the transaction if it exists and closes the connection.

The C# code is shown in Example 6-39.

Example 6-39. File: UsingLockingHintsForPessimisticLockingForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; 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; String sqlText = "SELECT * FROM Orders WITH "; // Add pessimistic locking as specified by user. if(updLockRadioButton.Checked) sqlText += "(UPDLOCK)"; else if(holdLockRadioButton.Checked) sqlText += "(HOLDLOCK)"; ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.