[ASP.NET] ADO.NET執行SQL指令並加入Transaction的範例

ADO.NET執行SQL指令並加入Transaction的範例

常常會用到的一段程式碼,貼上來與大家分享

前置:

using System.Data.SqlClient;         // ADO.NET
using System.Text;                          // StringBuilder
using System.Configuration;           // 取讀連接字串用 (From web.config)

 

程式碼:

        StringBuilder sb = new StringBuilder("");

        sb.AppendLine(@"
            INSERT INTO [TableName]
                   ([A]
                   ,[B]
                   )
             VALUES
                   ('A1'
                   ,'B2');
        "); // SQL command 1

        sb.AppendLine(@"
            INSERT INTO [TableName]
                   ([A]
                   ,[B]
                   )
             VALUES
                   ('A2'
                   ,'B2');
        "); // SQL command 2

        SqlConnection updateSc = new SqlConnection( ConfigurationManager.ConnectionStrings["連結字串名"].ConnectionString );
        SqlCommand updateCom = new SqlCommand(sb.ToString(), updateSc);
        updateSc.Open();
        SqlTransaction trans = updateSc.BeginTransaction();
        updateCom.Transaction = trans;

        bool pass = false;
        try
        {
            updateCom.ExecuteNonQuery();
            trans.Commit();
            pass = true;
        } // try
        catch (Exception excep)
        {
            trans.Rollback();  // 出現例外就rollback
            Response.Write("資料更新失敗, exception : " + excep.Message);
        } // catch
        finally
        {
            updateSc.Close();
            updateCom.Dispose();
            updateSc.Dispose();
            trans.Dispose();
        } // finally

        if (pass)
            Response.Write("資料更新完成");

 

--

不斷學習,精進自我

Herbert Fang