首页产品库评测行情新闻|手机数码笔记本台式机DIY硬件数字家庭数码相机办公外设|软件下载游戏开发|社区

更多

数码相机
MP4
LCD
机箱
音箱

天极网 > 软件频道>在C#中使用COM+实现事务控制

在C#中使用COM+实现事务控制

2003-10-11 11:47作者:candy出处:论坛责任编辑:方舟



  .NET技术是微软大力推广的下一代平台技术,自从.NET技术架构的正式发布,此项技术也逐渐走向成熟和稳定。按照微软的平台系统占有率,我们不难想象得到,在未来的一两年内.NET技术必定会势如破竹一般的登上主流的技术平台,而一个新的技术平台得以快速发展的最重要的前提是:他不会彻底的摒弃以前的技术,这一点对于.NET技术来说指的就是COM/COM+技术了。

  一般来说,在IT技术界以及硬件产业,技术的更新换代速度非常得惊人,而惯例是所有的新技术都会遵循向下兼容的原则,但是.NET技术不仅仅做到了这一点,.NET甚至实现了相互之间的各自调用,这一点是非常难能可贵的。也就是说,不但我们可以在.NET组件中调用COM组件,同时也可以在COM组件中正常的调用.NET组件。这点带来的好处是显而易见的,一方面我们可以保持现有的技术资源,另一方面,在现有资源中可以利用.NET所带来的各种新技术。

  一般的数据库事务控制要求事务里所做的操作必须在同一个数据库内,这样在出现错误的时候才能回滚(RllBack)到初始状态。这就存在一个问题,在分布式应用程序中,我们往往需要同时操作多个数据库,使用数据库本身的事务处理,很难满足程序对事务控制的要求。在COM+中,提供了完整的事务服务,我们可以利用它来完成在分布式应用程序中的事务控制。

  具体过程如下

  一:用VS.NET生成一个类库 。

  二:添加对System.EnterpristServices的引用,具体步骤

  菜单:(项目-添加引用-在.NET选项卡选择System.EnterpristServices-确定)

  三:构建类

  1:源程序

using System;
using System.EnterpriseServices;
using System.Data.SqlClient;
using System.Reflection;

namespace COMPlusSamples
{
//表明需要事务支持
[ Transaction(TransactionOption.Required) ]
//声明为服务器应用程序,还可以选择Library,表示为库应用程序
[assembly: ApplicationActivation(ActivationOption.Server)]
//描述信息
[assembly: Description("sample")]

public class TxCfgClass : ServicedComponent
{
private static string init1 = "user id=sa;password=;initial catalog=pubs;data source=(local)";

private static string init2 = "user id=sa;password=;initial catalog=NorthWind;data source=(local)";

private static string add1 = "insert into authors('au_lname','au_fname') values('test1', 'test2')";

private static string add2 = "insert into sample values('test1',22)";
//the error sql statement
//there is not table “sample”

public TxCfgClass() {}

private void ExecSQL(string init, string sql)
{
SqlConnection conn = new SqlConnection(init);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

//添加一条记录到数据库
public void Add()
{
try
{
//在一数据库中插入一条记录

ExecSQL(init1, add1);
Console.WriteLine("the operation in the same database completely");

//在另外一个数据库中插入两条记录
//这次执行的是一个错误的SQL语句

ExecSQL(init2, add2);
Console.WriteLine("the operation in the other database
completely");

Console.WriteLine("Record(s) added, press enter...");
Console.Read();

}
catch(Exception e)
{
//事务回滚
ContextUtil.SetAbort();
Console.WriteLine("Because there are some errors in the operation ,so transcation abort");
Console.WriteLine("The error is " + e.Message);
Console.WriteLine("abort successfully");
Console.Read();
}
}
}
}

共2页。 1 2 :

关注此文的读者还看过:

返回软件频道首页

共2页。 12下一页

软件频道最新更新

热点推荐

天极服务|关于我们|About us|网站律师|RSS订阅|友情合作|加入我们|天极动态|网站地图|意见反馈|MSN/QQ上看天极
Copyright (C) 1999-2012 Yesky.com, All Rights Reserved 版权所有 天极网络