在项目中添加对system.transactionScope程序集的引用 protected void Button1_Click(object sender, EventArgs e) { //两个连接字符串,连接到两个不同的数据库 string s1 = ConfigurationManager.ConnectionStrings["database"].ConnectionString; string s2 = ConfigurationManager.ConnectionStrings["database2"].ConnectionString; SqlConnection connection1 = new SqlConnection(s1); SqlConnection connection2 = new SqlConnection(s2); SqlCommand command = new SqlCommand(); command.CommandText = "insert into products (ProductID, ProductName, Price, Stock) " + "values('P101','新产品','ok',200)"; SqlCommand command1 = new SqlCommand(); command.CommandText = "insert into products (ProductID, ProductName, Price, Stock) " + "values('P101','新产品',3,200)"; using (TransactionScope tran = new TransactionScope()) { string message = ""; try { //command使用第一个连接,更新第一个数据库 connection1.Open(); command.Connection = connection1; command.ExecuteNonQuery(); //让command1使用第二个连接,更新第二个数据库 connection2.Open(); command1.Connection = connection2; command1.ExecuteNonQuery(); message = "保存成功"; //提交事务 tran.Complete(); } catch (Exception ex) { message = "保存用户信息过程中出错。事务回滚"; } finally { command.Dispose(); tran.Dispose(); if (connection1.State == ConnectionState.Open) connection1.Close(); if (connection2.State == ConnectionState.Open) connection2.Close(); } Page.ClientScript.RegisterStartupScript(this.GetType(),"Register","<mce:script type="text/javascript"><!-- alert(/"" + message+ "/"); // --></mce:script>"); }