C#中連線SqlServer資料庫並且使用事務和using語句的例項
阿新 • • 發佈:2019-01-08
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace test2 { class Program { static void Main(string[] args) { string connString = "Data Source=127.0.0.1;" + "Persist Security Info=True;" + "Initial Catalog=TestSql;" + "Integrated Security=false;" + "User ID=sa;" + "Password=root123;"; using (SqlConnection conn = new SqlConnection(connString)) //使用using語句塊,可確保關閉資料庫連線 { conn.Open(); Console.WriteLine("open database successfully!!!"); SqlCommand command = conn.CreateCommand(); SqlTransaction tx; tx = conn.BeginTransaction("SampleTransaction");//啟動一個本地事務管理 //為了將要發生的本地事務,必須將Transaction物件和SqlConnection物件賦值給SqlCommand物件 command.Connection = conn;//指定要執行資料操作的資料來源 command.Transaction = tx;//指定執行資料命令登記的事務物件 try { command.CommandText = "insert into employee (username,password) values('LiuYe','456')"; int rowsReturned = command.ExecuteNonQuery(); Console.WriteLine("{0}記錄已更新", rowsReturned); //提交事務 tx.Commit(); Console.WriteLine("record is written to database."); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.GetType()); Console.WriteLine("connection Exception!!!"); try { //不成功時回滾 tx.Rollback(); } catch (Exception ex) { //這個catch塊處理任何回滾失敗的異常,例如資料庫斷開的連線。 Console.WriteLine("Rollback Exception Type:{0}", ex.GetType()); Console.WriteLine("Message:{0}", ex.Message); } } } } } }