Pessimistic locking is not supported by the data providers because connection is always open so we use datasets for this purpose.
You can achieve this with the help of transactions by providing proper isolation.
Pessimistic approach follows the way of isolation for providing concurrency, so that is why we provide isolation at the application and the database level.
Isolation Level
Read
Update
Insert
Read Uncommitted
Reads data which is yet not committed.
Allowed
Allowed
Read Committed ( Default)
Reads data which is committed.
Allowed
Allowed
Repeatable Read
Reads data which is committed.
Not Allowed
Allowed
Serializable
Reads data which is committed.
Not Allowed
Not Allowed
void TestPessimisticConcurrency()
{
try
{
//Create a connection object
string ConnectionString = "Integrated security = SSPI;" +
"Initial Catalog = Northwind;" + "Data Source = localhost;";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
// Create a transaction that locks the records of the query
SqlTransaction tr = conn.BeginTransaction
(IsolationLevel.RepeatableRead, "test");
//Create a command that updates the order of
//the database using the transaction
SqlCommand cmd = new SqlCommand("UPDATE Orders SET " +
"ShippedDate = '5/10/01', ShipCity = 'Columbus' WHERE" +
"OrderID = 10248", conn, tr);
// Execute the update
cmd.ExecuteNonQuery();
// Generate Message
MessageBox.Show("Wait for KeyPress.");
tr.Commit(); // Transaction is committed
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
0 Comment(s)