当前位置: 移动技术网 > IT编程>开发语言>c# > C#处理Access中事务的方法

C#处理Access中事务的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#处理access中事务的方法。分享给大家供大家参考。具体如下:

access不能像sql server一样直接执行多条语句,但是把多条语句绑成事务还是可以一起执行的. 所谓事务,就是把多件事情当做一件事情来处理。也就是大家同在一条船上! 由一个事务来完成多个表的同步操作,要么都执行成功,要么都不成功.下面举个例子,用c#实现access数据库事务的处理方法: 向一个表提交数据,同时更新另一个表中的数据

using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.data.oledb;
public partial class _default : system.web.ui.page 
{
  protected void page_load(object sender, eventargs e)
  {
  }
  protected void button1_click(object sender, eventargs e)
  {
    string id = "";
    string strcon = system.configuration.configurationmanager.appsettings["connectstr"].tostring();
    oledbconnection con = new oledbconnection(strcon);   
    oledbdataadapter adp = new oledbdataadapter(); 
    oledbdataadapter adp1 = new oledbdataadapter();
    try
    {
      con.open();
      oledbtransaction tra = con.begintransaction(); //创建事务,开始执行事务
      adp = new oledbdataadapter("select * from 序号表", con);
      adp.selectcommand.transaction = tra;
      adp1=new oledbdataadapter("select * from 节目表", con);
      adp1.selectcommand.transaction = tra;
      oledbcommandbuilder thisbuilder = new oledbcommandbuilder(adp);  
      oledbcommandbuilder thisbuilder1 = new oledbcommandbuilder(adp1); 
      dataset ds = new dataset();
      adp.fill(ds,"aa");//添加数据集
      id = ds.tables["aa"].rows[0][1].tostring();
      int64 s = 0;
      s = convert.toint64(id) + 1;
      id = s.tostring("0000000#");
      ds.tables["aa"].rows[0][1] = id; 
      adp.update(ds,"aa");//执行修改一个表的事务
      adp1.fill(ds,"bb");
      datarow dr=ds.tables["bb"].newrow();
      dr["proid"]=id;
      dr["proname"]="proname";
      dr["protime"]="2";
      dr["proisfinish"]="3";
      dr["probgcolor"]="4";
      dr["probgpic"]="5";
      dr["prostyle"]="6";
      dr["missionname"]="7";
      dr["prodescription"]="8";
      ds.tables["bb"].rows.add(dr);
      adp1.update(ds,"bb");
      tra.commit();//关闭事务
    }
    catch (exception ex)
    {
    }
    finally
    {
      con.close();
    }
}

注:access的事务不支持自动锁定(经试验已经证实),因此access最好用于本机的程序,b/s中做好不要用,除非你不用事务处理~~!

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网