本文实例讲述了C#处理Access中事务的方法。分享给大家供大家参考。具体如下:
Access不能像SQL server一样直接执行多条语句,但是把多条语句绑成事务还是可以一起执行的. 所谓事务,就是把多件事情当做一件事情来处理。也就是大家同在一条船上! 由一个事务来完成多个表的同步操作,要么都执行成功,要么都不成功.下面举个例子,用C#实现Access数据库事务的处理方法: 向一个表提交数据,同时更新另一个表中的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
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#程序设计有所帮助。