步步为营-50-事务
生活随笔
收集整理的這篇文章主要介紹了
步步为营-50-事务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
說明:比較常用
1 事務的四大特性:
1.1?原子性atomicity?一個事務中包含的多個SQL語句,要么同時成功,要么同時失敗.
1.2 一致性consistency?事務必須使數據庫從從一個一致性狀態變成另外一個一致性狀態.(銀行轉賬)
1.3?隔離性?isolation?各個事務執行互不干擾(鎖)
1.4 持久性?durability?對數據庫中數據的改變是永久性的.
2?事務的使用
2.1?在SQLServer中
select * from UserInfo --01 事務 --01-01 開啟事務(try---catch)捕獲異常 BEGIN trybegin transactionUpdate UserInfo set StuName = N'逍遙小天狼' where EmpId = 10Update UserInfo set StuAge = N'年齡' where EmpId = 11--01-02 提交事務commit transaction END tryBEGIN catch--01-03回滾事務rollback tran; END catch View Code2.2?在C#中
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TransactionDemo { class Program { static void Main(string[] args) { #region 01事務 //01 連接字符串 string connstr = "Data Source=127.0.0.1;uid=sa;pwd=sa;Initial Catalog=DemoDB;"; using (SqlConnection conn = new SqlConnection(connstr)) { using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); //02-01創建事務 SqlTransaction tran = conn.BeginTransaction(); //02-02 把事務給cmd的事務屬性 cmd.Transaction = tran; try { cmd.CommandText = @"Update UserInfo set StuName = N'逍遙小天狼' where EmpId = 10 Update UserInfo set StuAge = 111 where EmpId = 11"; cmd.ExecuteNonQuery(); //事務提交 tran.Commit(); } catch (Exception) { tran.Rollback(); } } Console.Read(); #endregion } } } } View Code3?事務的調用--另一種方法
3.1?添加引用,引入命名空間using System.Transactions;
#region 02事務try{using (TransactionScope scope = new TransactionScope()){using (SqlConnection conn = new SqlConnection(connstr)){using (SqlCommand cmd = conn.CreateCommand()){conn.Open();cmd.CommandText = @"Update UserInfo set StuName = N'逍遙小天狼' where EmpId = 10Update UserInfo set StuAge = 111 where EmpId = 11";cmd.ExecuteNonQuery();Console.WriteLine("執行成功!");}}//提交事務 scope.Complete();}}catch (Exception){Console.WriteLine("異常");}Console.Read();#endregion 事務2?
轉載于:https://www.cnblogs.com/YK2012/p/6818997.html
總結
以上是生活随笔為你收集整理的步步为营-50-事务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实验室管理软件 费用报销 项目经费 试剂
- 下一篇: 实验室仪器设备管理方案