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层

  • 相关阅读:
    Azure PowerShell (2) 修改Azure订阅名称
    Windows Azure Platform Introduction (11) 了解Org ID、Windows Azure订阅、账户
    Azure PowerShell (3) 上传证书
    Azure PowerShell (1) PowerShell入门
    Windows Azure Service Bus (2) 队列(Queue)入门
    Windows Azure Service Bus (1) 基础
    Windows Azure Cloud Service (10) Role的生命周期
    Windows Azure Cloud Service (36) 在Azure Cloud Service配置SSL证书
    Android studio 使用心得(一)—android studio快速掌握快捷键
    android 签名、混淆打包
  • 原文地址:https://www.cnblogs.com/soundcode/p/2056871.html
Copyright © 2011-2022 走看看