在很多场合比如电子交易会用到事务,在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...");
using (con) ...{
con.Open();
//事务实例的获得
trans = con.BeginTransaction();
try ...{
cmd.Connection = con;
cmd.Transaction = trans; //向SqlCommand注册事务
cmd.CommandText = "use nyzhl";
cmd.ExecuteNonQuery();
cmd.CommandText = "update [users] set [age]=[age]+1 where uid=''xiaobai''";
cmd.ExecuteNonQuery();
//提交事务
trans.Commit();
}
catch(Exception e) ...{
//回滚事务
trans.Rollback();
Console.WriteLine("Error!Transaction has RolledBack. "+e.Message);
}
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);
//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
文章出处:http://www.diybl.com/course/4_webprogram/asp.net/asp_netxl/2007125/90383.html