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+的開銷。 */