ado.net1.X的事务处理
ado.net2.0的简单事务处理:(using System.Transactions;)
ado.net2.0的分布式事务处理:(using System.Transactions;)
1
SqlConnection myConnection = new SqlConnection("Server=(local);Initial Catalog=Demo24;uid=sa;pwd=111;");
2
myConnection.Open();
3
// 启动一个事务
4
SqlTransaction myTrans = myConnection.BeginTransaction();
5
6
7
// 为事务创建一个命令
8
SqlCommand myCommand = new SqlCommand();
9
myCommand.Connection = myConnection;
10
myCommand.Transaction = myTrans;
11
try
12
{
13
myCommand.CommandText = "Insert into tbUserInfo (UserName, UserPass,Birthday,Score) VALUES ('成龙', '111','1966-1-1',540)";
14
myCommand.ExecuteNonQuery();
15
//myTrans.Commit();
16
myCommand.CommandText = "Insert into tbUserInfo (UserName, UserPass,Birthday,Score) VALUES ('王五', '222','198834',550)";
17
myCommand.ExecuteNonQuery();
18
myTrans.Commit();
19
MessageBox.Show("成功写入记录!");
20
}
21
catch
22
{
23
myTrans.Rollback();
24
MessageBox.Show("写入数据库失败!");
25
}
26
finally
27
{
28
myConnection.Close();
29
}

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

ado.net2.0的简单事务处理:(using System.Transactions;)
1
string strCon = "Server=(local);Initial Catalog=Demo24;uid=sa;pwd=111;";
2
try
3
{
4
5
using (TransactionScope ts = new TransactionScope())
6
{
7
using (SqlConnection myConnection = new SqlConnection(strCon))
8
{
9
myConnection.Open();
10
using (SqlCommand myCommand = myConnection.CreateCommand())
11
{
12
13
myCommand.CommandText = "Insert into tbUserInfo (UserName, UserPass,Birthday,Score) VALUES ('成龙', '111','1966-1-1',540)";
14
myCommand.ExecuteNonQuery();
15
//myTrans.Commit();
16
myCommand.CommandText = "Insert into tbUserInfo (UserName, UserPass,Birthday,Score) VALUES ('王五', '222','1988-3-4',550)";
17
myCommand.ExecuteNonQuery();
18
ts.Complete();
19
}
20
}
21
}
22
}
23
catch
24
{
25
MessageBox.Show("程序出错!事务没有成功!");
26
}

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

ado.net2.0的分布式事务处理:(using System.Transactions;)
1
using (TransactionScope ts = new TransactionScope())
2
{
3
using (SqlConnection myConnection = new SqlConnection(strCon))
4
{
5
myConnection.Open();
6
using (SqlCommand myCommand = myConnection.CreateCommand())
7
{
8
9
myCommand.CommandText = "Select count(*) from tbUserInfo";
10
int nCount = (int)myCommand.ExecuteScalar();
11
MessageBox.Show(nCount.ToString());
12
}
13
}
14
using (SqlConnection myConnection = new SqlConnection(strCon))
15
{
16
myConnection.Open();
17
using (SqlCommand myCommand = myConnection.CreateCommand())
18
{
19
20
myCommand.CommandText = "Select count(*) from tbUserInfo";
21
int nCount = (int)myCommand.ExecuteScalar();
22
MessageBox.Show(nCount.ToString());
23
24
}
25
}
26
ts.Complete();
27
}
28
}
29
catch
30
{
31
MessageBox.Show("程序出错!事务没有成功!");
32
}

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
