使用.Net2.0的事务

来源:互联网 发布:禁毒知识网络竞赛 编辑:程序博客网 时间:2024/05/18 01:12
 在2.0框架下,可以使用System.Transactions这个命名空间下的一些类,其中System.Transactions.TransactionScope,实现了隐式的事务处理方式,可以判断事务的类型来使用本地级事务或者是分布式事务.我的测试代码如下:
            try
            
{
                
using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                
{
                    
using (System.Data.SqlClient.SqlConnection sql1 = new System.Data.SqlClient.SqlConnection(@"Data Source=LYSERVER/LYSERVER;Initial Catalog=pubs;Persist Security Info=True;User ID=sa"))
                    
{
                        sql1.Open();
                        System.Data.SqlClient.SqlCommand cmd 
= new System.Data.SqlClient.SqlCommand();
                        cmd.Connection 
= sql1;
                        cmd.CommandText 
= "INSERT INTO stores(stor_id,stor_name,stor_address,city,state,zip) values('8888','测试分布式事务','沈阳市三好街','沈阳','LY','111')";
                        cmd.ExecuteNonQuery();
                        sql1.Close();
                    }

                    
if (MessageBox.Show("您要中断对本地数据库的访问吗?""", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    
{
                        
throw new Exception("用户中断,自动回滚全部事务!");
                    }

                    
using (System.Data.SqlClient.SqlConnection sql1 = new System.Data.SqlClient.SqlConnection(@"Data Source=wu;Initial Catalog=pubs;Integrated Security=True"))
                    
{
                        sql1.Open();
                        System.Data.SqlClient.SqlCommand cmd 
= new System.Data.SqlClient.SqlCommand();
                        cmd.Connection 
= sql1;
                        cmd.CommandText 
= "INSERT INTO stores(stor_id,stor_name,stor_address,city,state,zip) values('8888','测试分布式事务','沈阳市三好街','沈阳','LY','111')";
                        cmd.ExecuteNonQuery();
                        sql1.Close();
                    }

                    scope.Complete();
                    MessageBox.Show(
"commited");
                }

            }

            
catch (Exception ex)
            
{
                MessageBox.Show(ex.Message);
            }
注意:在使用System.Transactions时,VS2005并没有引用其相应的Dll,需要手动的引用System.Transaction.dll.
原创粉丝点击