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
SELECTstatement to retrieve the Orders table from the Northwind database. A locking hint, eitherUPDLOCKorHOLDLOCK, is added to the statement as specified. AConnectionis opened and aTransactionstarted on it with an isolation level ofReadCommitted. ADataAdapteris used on the transacted connection to fill aDataTable. ACommandBuilderis 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.ClosingRolls 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)"; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access