1. 程式人生 > >C#中開啟事務

C#中開啟事務

在C#中開啟事務的步驟

01.呼叫SqlConnection物件的BeginTransaction()方法,建立一個SqlTransaction物件,標誌事務開始。

02.將建立的SqlTransaction物件分配給要執行的SqlCommand的Transaction屬性。

03.呼叫相應的方法執行SqlCommand命令。

04.呼叫SqlTransaction的Commit()方法完成事務。或呼叫Rollback()方法終止事務。  

4.在進行事務操作中的注意點

01.在呼叫BeginTransaction()方法開始事務之前,要開啟資料庫連線,否則出現異常。

02.如果在事務的Commit()方法或RollBack()方法執行前資料庫連線斷開或關閉,則事務將回滾。

 

//準備連線字串
            string str = "data source=.;initial catalog=Myschool;uid=sa;pwd=123";
            //建立資料庫連線物件
            SqlConnection con = new SqlConnection(str);
            //sql語句:新增一條記錄到年級表
            string sql = "insert into grade values(@gradename)";
            //建立SqlParameter物件,設定引數
            SqlParameter sp = new SqlParameter("@gradename", txtgradename.Text);
            //建立命令物件
             SqlCommand cmd = new SqlCommand(sql, con);
             //通過Parameter集合的add()方法天填充引數集合
             cmd.Parameters.Add(sp);
            //開啟連線
             con.Open();
            //預設讓SqlTransaction物件為空
             SqlTransaction trans = null;
            //開啟事務:標誌事務的開始
             trans = con.BeginTransaction();
            try
            {
                //將建立的SqlTransaction物件分配給要執行的sqlCommand的Transaction屬性
                cmd.Transaction = trans;
                //執行sql如果新增成功放回1
                int count=cmd.ExecuteNonQuery();
                if (count > 0)
                {
                    MessageBox.Show("成功");
                    //事務提交
                    trans.Commit();
                }
                else 
                {
                    MessageBox.Show("失敗");
                    //事務回滾
                    trans.Rollback();
                }
            }
            catch (Exception)
            {
                //如果某個環節出現問題,則將整個事務回滾
                trans.Rollback();
            }

出處:
https://www.cnblogs.com/jiuyueBlog/p/9109860.html