zoukankan      html  css  js  c++  java
  • ASP.NET页面级别的事务

    ASP.NET事务可以说是在.NET平台上事务实现方式最简单的一种,你仅仅需要一行代码即可。在aspx的页面声明中加一个额外的属性,即事务属性Transaction="Required",它有如下的值:Disabled(默认)、NotSupported、Supported、Required和RequiresNew,这些设置和COM+及企业级服务中的设置一样,典型的一个例子是如果你想在页面上下文中运行事务,那么要将其设置为Required。如果页面中包含有用户控件,那么这些控件也会包含到事务中,事务会存在于页面的每个地方。

    代码示例:

    页面声明Transaction="Required":

    <%@ Page Transaction="Required"  Language="C#" AutoEventWireup="true"

    CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication4.WebForm3" %>

    页面引用:using System.EnterpriseServices;。

    然后,数据操作代码:

    protected void Button1_Click(object sender, EventArgs e)

    {

        try

        {

            Work1();

            Work2();

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

        }

        catch (System.Exception except)

        {

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

            Response.Write(except.Message);

        } 

    private void Work1()

    {

        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 Work2()

    {

        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();

    }

    ContextUtil是用于获取 COM+ 上下文信息的首选类。由于此类的成员全部为static,因此在使用其成员之前不需要对此类进行实例化。

    ASP.NET页面事务的优势和限制如下。

    l  优势:实现简单,不需要额外的编码。

        l限制:页面的所有代码都是同一个事务,这样的事务可能会很大,而也许我们需要的是分开的、小的事务实现在Web层

  • 相关阅读:
    MyBatis(第三方缓存整合原理&ehcache适配包下载)
    MyBatis(缓存机制)
    MyBatis(动态SQL2)
    MyBatis(动态SQL)
    MyBatis(映射文件中使用foreach标签时报错,属性collection的问题)
    MyBatis映射文件(编写SQL语句;可有可无(无的时候,使用注解编程))
    Python virtualenv with Sublime Text 3
    python & mongo问题记录
    CentOS On VirtualBox
    MySQL GROUP BY用法
  • 原文地址:https://www.cnblogs.com/soundcode/p/2056871.html
Copyright © 2011-2022 走看看