在很多場合比如電子交易會用到事務,在C#中,事務的操作非常簡單。通過System.Data.SqlClIEnt.SqlTransaction類實現。
SqlTransaction實例的獲得:SqlConnection.BeginTransaction();
通過設置Command.Transaction屬性 在連接中注冊事務
Command.Transaction = SqlConnection.BeginTransaction();
SqlTransaction.Commit();提交事務
SqlTransaction.Rollback();回滾事務
例如下面程序,ExecTrans函數執行事務,將用戶xiaobai的年齡加1.
程序源代碼 TansactionTest.cs
using System;
using System.Data.SqlClIEnt;
public class TransactionTest ...{
//MS Sql Server Connection String
private string sqlStr = "Data Source=.;Integrated Security=SSPI";
//Get MS Sql Server Connection.
private SqlConnection GetCon() ...{
return new SqlConnection(this.sqlStr);
}
//事務的執行
private void ExecTrans() ...{
SqlConnection con = this.GetCon();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = null;
Console.WriteLine("Begin to Execute Transaction...");
finally ...{
if(con!=null) con.Close();
}
}
}
//Print data from Database
private void WriteInfor() ...{
SqlConnection con = this.GetCon();
SqlCommand cmd = new SqlCommand();
SqlDataReader sdr = null;
cmd.Connection = con;
Console.WriteLine("User Information(UserID, Age):");
con.Open();
cmd.CommandText = "use nyzhl";
cmd.ExecuteNonQuery();
cmd.CommandText = "select * from [users]";
sdr = cmd.ExecuteReader();
while(sdr.Read()) ...{
string uid = sdr.GetString(0);
&
nbsp; //Sql Sever中的tinyint型 在C#中對應Byte型(都占一個字節)
int age = sdr.GetByte(1);
Console.WriteLine(uid+" : "+age);
}
sdr.Close();
sdr.Dispose();
con.Close();
con.Dispose();
}
//Entry of Application
public static void Main() ...{
TransactionTest test = new TransactionTest();
test.WriteInfor();
test.ExecTrans();
test.WriteInfor();
}
}
數據庫及表結構
use master
go
create database nyzhl
go
use nyzhl
go
create table users
(
uid varchar(255) primary key,
age tinyint
)
go
insert into users values(''nyzhl'',22)
go
insert into users values(''xiaobai'',20)
go