資料庫併發控制幾隻——事務

wzm10455發表於2013-05-16

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

/*事務是一組被當作一個單元的操作,它們在執行時要麼全部成功,要麼全部失敗。

例如轉帳操作

事務的兩個層次
    資料庫級的事務
    ADO.NET事務
 如果在某個操作中需要對資料庫進行多次更新,則必須使用事務。
SqlTransaction myTransaction
      =myConnection.BeginTransaction();
try
{     ...
       myCommand = new OleDbCommand(cmdstr,   myConnection,myTransaction);
       ...
      myTransaction.Commit();
}
catch (Exception es)
{
      myTransaction.Rollback();
}
*/
namespace Transaction
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
            SqlConnection myconn = new SqlConnection(connectionString);

            try
            {
                myconn.Open();

                SqlTransaction myTransaction = myconn.BeginTransaction();//新建一個事務

                try
                {
                    string cmdstr = "update Account set money=money-100 where Id='1'";
                    SqlCommand mycmd = new SqlCommand(cmdstr,myconn,myTransaction);
                    mycmd.ExecuteNonQuery();

                    throw new Exception();//丟擲異常,會直接被catch捕獲,處理
                    string cmdstr2="update Account set money=money+100 where Id='2'";
                    SqlCommand mycmd1 = new SqlCommand(cmdstr2, myconn, myTransaction);
                    mycmd1.ExecuteNonQuery();

                    myTransaction.Commit();//只有執行這句後資料庫裡面的資料才有可能會改變
                }
                catch(Exception ee)
                {
                    myTransaction.Rollback();//進行回滾
                    MessageBox.Show("轉賬失敗,正在回滾!");
                }


                myconn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("資料庫連線失敗!");
            }

        }
    }
}

相關文章