c#事务用法

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
ado.net2.0的SqlTransaction使用方法
/////ado.net1.0中使用Transacation(事务)
string connectionString = "database=Northwind;pwd=admin;uid=sa;server=DATABASE-VPC\\SQL2005";
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlTransaction transaction = conn.BeginTransaction();
                try
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "";
                        cmd.Transaction = transaction;
                        cmd.ExecuteNonQuery();
                        transaction.Commit();//提交事务
                    }
                }
                catch
                {
                    transaction.Rollback();//事务回滚
                }
/////2.0中使用事务
 string connectionString = "database=Northwind;pwd=admin;uid=sa;server=DATABASE-VPC\\SQL2005";
            string connectionStringTwo = "database=Test;pwd=admin;uid=sa;server=DATABASE-VPC\\SQL2005";
            using (TransactionScope transaction = new TransactionScope())//使用事务
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connectionString))
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.CommandText = "insert into [member] (name) values (‘test‘)";
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                    using (SqlConnection conn = new SqlConnection(connectionStringTwo))
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.CommandText = "insert into [member] (name) values (‘test‘)";
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                    transaction.Complete();//就这句就可以了。
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
/*ado.net1.0与ado.net2.0中对比
1.0中不能跨数据库,速度慢
2.0中可以跨数据库,2.0中不再使用com+,速度比1.0快50%(因为它不用把大量的时间消耗在查找在com+中)
2.0中的事务会自动判断使用何种事务(不用您考虑是简单事务还是分部式事务)。
2.0中的Transactions新添加了命名空间。没有com+注册和com+的开销。
*/

  

c#事务用法

上一篇:SWPUCTF_2019_p1KkHeap(tcache_entry)


下一篇:Redis数据结构(六)-压缩列表ziplist