C#分布式事务隔离级别问题?如何解释不同的隔离级别,结合案例。

来源:互联网 发布:mac上的flash怎么卸载 编辑:程序博客网 时间:2024/04/27 23:14

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Transactions;

namespace MyFriend
{
   
/*
*      --隔离级别
        级别一 read uncommitted         System.Transactions.IsolationLevel.ReadUncommitted      --未提交读

        级别二 read committed           System.Transactions.IsolationLevel.ReadCommitted        --提交读

        级别三 repeatable read          System.Transactions.IsolationLevel.RepeatableRead       --可重复读

        级别四 serializable             System.Transactions.IsolationLevel.Serializable         --可串行读
*/
   
public partial class frmIsolationLevel : Form
    {
       
public frmIsolationLevel()
        {
            InitializeComponent();
        }
       
private static string GetConnectionString(int i)
        {
           
if (i == 1)
               
return "Data Source=.;Initial Catalog=MyFriend;User ID=sa;Password=123456";
           
else
               
return "Data Source=.;Initial Catalog=student;User ID=sa;Password=123456";
        }

       
private void button1_Click(object sender, EventArgs e)
        {
           
string str1 = "insert into depart  values('市场部3',19,'1982-02-03')";
           
string str2 = "insert into info    values('拉灯3','078889897878','13989889899','阿富汗捣蛋部队','999','技术部')";

            SqlConnection cn1
= new SqlConnection(GetConnectionString(1));  //连接库1
            cn1.Open();
            TransactionOptions op
= new TransactionOptions();
           
//op.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;  //提交读
            op.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead;  //提交读

           
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, op))    //创建事务代码块
            {
                SqlCommand cmd1
= new SqlCommand(str1, cn1);
               
int rowsUpdated1 = cmd1.ExecuteNonQuery();
               
if (rowsUpdated1 > 0)
                {
                    SqlConnection cn2
= new SqlConnection(GetConnectionString(1));//连接库2.
                    cn2.Open();
                    SqlCommand cmd2
= new SqlCommand(str2, cn2);

                   
int rowsUpdated2 = cmd2.ExecuteNonQuery();
                   
if (rowsUpdated2 > 0)
                    {
                        ts.Complete();
                        MessageBox.Show(
"事务提交完成!");
                    }
                    cn2.Close();
                }
            }
            cn1.Close();
        }

    }
}
//*************db如下:

原创粉丝点击