本文實例講述了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#程序設計有所幫助。
新聞熱點
疑難解答