DEV Community

DotNet Full Stack Dev
DotNet Full Stack Dev

Posted on

πŸ”’ C# Tip: SQL Isolation Levels for Data Consistency

Understanding SQL isolation levels is crucial for maintaining data integrity in concurrent environments!

πŸ“ŒExplore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Sharing would be appreciated! πŸš€

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        using (var connection = new SqlConnection("YourConnectionString"))
        {
            connection.Open();

            // Use ReadCommitted to prevent dirty reads
            using (var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                try
                {
                    // Sample database operation
                    using (var command = new SqlCommand("SELECT * FROM YourTable", connection, transaction))
                    {
                        var reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            Console.WriteLine(reader["YourColumn"]);
                        }
                    }

                    // Commit the transaction
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // Rollback if there's an error
                    transaction.Rollback();
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

πŸ” Highlights:

  • Read Uncommitted: Allows dirty reads πŸ₯΄
  • Read Committed: Prevents dirty reads βœ…
  • Repeatable Read: Locks data for reading πŸ”’
  • Serializable: Highest level of isolation πŸ†

Choose wisely to balance performance and consistency!

Top comments (0)