C#實現數據庫事務處理的簡單示例代碼

C#實現數據庫事務處理的簡單示例代碼
最近做了個小項目,其中要對兩個表同時進行插入insert操作處理,而且對它們的插入操作要麼全部成功,要麼都插入失敗,否則只插入一個表成功會引起數據庫的不一致。很顯然,這是一個事務處理(transcation),要麼commit成功,要麼則rollback。在代碼中,我利用的是C#中提供的Transcation類來實現,代碼如下:
private void btn_submit_Click(object sender, System.EventArgs e)
        {
            
string strconn = ConfigurationSettings.AppSettings["dsn"];
            SqlConnection cnn 
= new SqlConnection(strconn);
            SqlCommand cmd 
= new SqlCommand();
            SqlTransaction transaction 
= null;

            
try
            {
                cnn.Open();

                
// 先插入分店shop表,再插入經理Manager表,並將其作爲一個事務進行處理
                transaction = cnn.BeginTransaction();
                cmd.Transaction 
= transaction;
                cmd.Connection 
= cnn;

                
// 插入分店shop表
                string shopstr = "insert into shop values('" + tbx_shopid.Text + "','" + tbx_shopname.Text + "','" + tbx_shopaddress.Text + "','" + tbx_shopphone.Text + "')";
                cmd.CommandType 
= CommandType.Text;
                cmd.CommandText 
= shopstr;
                cmd.ExecuteNonQuery();

                
// 插入經理Manager表
                string managerstr = "insert into manager values('" + tbx_managerid.Text + "','" + tbx_managerpassword.Text + "','" + tbx_managername.Text + "','" + tbx_shopid.Text + "')";
                cmd.CommandType 
= CommandType.Text;
                cmd.CommandText 
= managerstr;
                cmd.ExecuteNonQuery();

                
// 提交事務
                transaction.Commit();
                lbl_msg.Text 
= "添加分店操作成功";
            }
            
catch(Exception ex)
            {
                lbl_msg.Text 
= "添加分店操作失敗";
                transaction.Rollback();
            }
            
finally
            {
                cnn.Close();
            }
        } 
 
發佈了19 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章