您的位置:首页 > 编程语言 > ASP

数据库开发之【ASP.NET页面级别的事务】

2013-11-09 15:51 393 查看
.NET开发常用的事务机制有以下几种:

【1】SQL和存储过程级别的事务;

【2】ADO.NET级别的事务;

【3】ASP.NET页面级别的事务;【本博客将介绍】

【4】企业级服务COM+事务;

【5】System.Transactions事务处理。

本章节将介绍ASP.NET页面级别的事务实现过程:

(1)在ASP.NET页面声明中添加一个额外的属性,如:

<%@ Page Transaction="Required"  Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs"
Inherits="WebApplication4.WebForm3" %> 

(2)后台页面引用:using System.EnterpriseServices;

(3)然后在后台代码中添加 提交事务 和 撤销事务 操作。

         try

            {

                //数据库操作方法,略                

                ContextUtil.SetComplete();//提交事务
            }

            catch (System.Exception except)

            {

                ContextUtil.SetAbort();//撤销事务
                Response.Write(except.Message);

            }

++++++++++++++++++++++++++++++++++++++++++++++++++++++

           华丽丽的分割线【实例演示】

----------------------------------------------------------------------------------------------

在前端页面添加事务属性:

<%@ Page Transaction="Required"  Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication4.WebForm3" %> 

引入命名空间:using System.EnterpriseServices;

public partial class WebForm3 : System.Web.UI.Page

    {

        // 5.4.3  Asp.Net页面级别的事务

        protected void Button1_Click(object sender, EventArgs e)

        {

            try

            {

                SQLWork1();//数据库操作1

                SQLWork2();//数据库操作2

                ContextUtil.SetComplete();//提交事务
            }

            catch (System.Exception except)

            {

                ContextUtil.SetAbort();//撤销事务

                Response.Write(except.Message);
            }

        }

        private void SQLWork1()

        {

            string conString = "data source=127.0.0.1;database=codematic;user id=sa;password=";

            SqlConnection myConnection = new SqlConnection(conString);

            string strSql = "Insert Into P_Category(CategoryId,Name)values('1','test1')";

            SqlCommand myCommand = new SqlCommand(strSql, myConnection);

            myConnection.Open();

            int rows = myCommand.ExecuteNonQuery();

            myConnection.Close();

        }

        private void SQLWork2()

        {

            string conString = "data source=127.0.0.1;database=codematic;user id=sa;password=";

            SqlConnection myConnection = new SqlConnection(conString);

            string strSql = "Insert Into P_Category(CategoryId,Name)values('2','test2')";

            SqlCommand myCommand = new SqlCommand(strSql, myConnection);

            myConnection.Open();

            int rows = myCommand.ExecuteNonQuery();

            myConnection.Close();

        }

     }

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 PS: ASP.NET页面级别的事务属性Transaction的属性值:Disabled(默认)、NotSupported、Supported、Required和RequiresNew
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐