在C# ADO.NET中处理并发冲突通常有两种方式:
string updateCommand = "UPDATE Table SET Column = @value WHERE ID = @id AND Version = @version";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(updateCommand, connection);
command.Parameters.AddWithValue("@value", updatedValue);
command.Parameters.AddWithValue("@id", id);
command.Parameters.AddWithValue("@version", currentVersion);
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 0)
{
// 处理并发冲突
}
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.Serializable);
try
{
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "SELECT * FROM Table WITH (UPDLOCK) WHERE ID = @id";
command.Parameters.AddWithValue("@id", id);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
// 更新数据
}
reader.Close();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
// 处理异常
}
}
以上是两种常见的处理并发冲突的方式,开发者可以根据具体情况选择合适的方式来处理数据更新时可能发生的并发冲突。