SQL SERVER-事務的使用
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
string source = "server=.;uid=sa;pwd=Server2012;database=D:\\DATABASE\\NORTHWND.MDF";
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
using (SqlConnection con = new SqlConnection(source))
{
try
{
con.Open();
string sql1 = "insert into Employees(FirstName,LastName) values('duan','xianmin')";
SqlCommand cmd = new SqlCommand(sql1, con);
cmd.ExecuteNonQuery();
Console.Read();//在此可以輸入enter繼續,或直接關閉來測試事務
string sql2 = "insert into Categories(CategoryName) values('Sea Food')";
cmd = new SqlCommand(sql2, con);
cmd.ExecuteNonQuery();
scope.Complete();//執行到這裡則提交,否則回滾;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
}