C#中事務機制的研究

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace TransactionPractice
{
    class Program
    {
        static void Main(string[] args)
        {
            TransactionTraining();
        }


        private static void TransactionTraining()
        {
            SqlConnection conn = new SqlConnection("server =.;database = zhao722;uid = sa;pwd = 3221682;");
            if (conn.State!= System.Data.ConnectionState.Open)
            {
                conn.Open();
            }
            //經過鏈接通道取得事務
            SqlTransaction tran = conn.BeginTransaction();

            SqlCommand cmd = conn.CreateCommand();

            try
            {
                //事務傳給sql操做語句
                cmd.Transaction = tran;

                cmd.CommandText = "update test2 set name = '這是新修改的各類姓名' ";


                cmd.ExecuteNonQuery();

                //此處注意,一次只能執行一行

                cmd.CommandText = "insert into test2(name,score,id) values('zhao','50',50)";

                //cmd.CommandText = "update test2 set name = '測試姓名' ";

                cmd.ExecuteNonQuery();


                //提交事務
                tran.Commit();
            }
            catch (Exception e)
            {
                tran.Rollback();
            }
            finally 
            {
                conn.Close();
            }
        }
    }
}
相關文章
相關標籤/搜索